mercredi 5 février 2020

MVC Query doesn't fetch all records from the database

The DB stores several accounts: [winnie, winnie9, winnie10], however the query only returns one record when I fetch the data. What would be the solution?

Model method:

protected function getApprovedUsers($login) {
        $sql = "SELECT `email`, `login`, `name`, `reg_date`, `pass`, `role` FROM `approved` WHERE `login` LIKE ?";
        $stmt = $this->connect()->prepare($sql);

        $stmt->execute([$login]);

        if($users = $stmt->fetchAll())
            return $users;

        return null;
    }

Controller call to the Model:

    public function getCertainApprovedUser($login) {
        $users = $this->getApprovedUsers($login);

        if(is_array($users) || is_object($users)) {
            foreach ($users as $user) {
                return array("email"=>$user["email"], "login"=>$user["login"], "pass"=> $user["pass"],
                    "name"=> $user["name"], "reg_date"=> $user["reg_date"], "role"=> $user["role"]);
            }
        }
        else {
            throw new Exception("Nothing to fetch");
        }
    }
}

Processing the data so that LIKE statement would work properly (%%):

$record = $userContr->getCertainApprovedUser("%$login%");

$someJSON = array(
    [
        "login"=>"{$record['login']}",
        "email"=>"{$record['email']}",
        "name"=>"{$record['name']}",
        "reg_date"=>"{$record['reg_date']}"
    ]
);

$newJSON = json_encode($someJSON);
echo $newJSON;



Aucun commentaire:

Enregistrer un commentaire