I have a function in my class which is not completed. I'm searching a way to do it all night long. Well I want to fetch all the result of a SELECT request to MYSQL using PDO in a OOP class/function.
Here my function
function select($query)
{
try
{
$sql = $this->connect->query($query);
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
return ????
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
I know that I can do it with a while loop, I tested a few options but most of the time I only got 1 result. Anyone a point for me, where I could start my search for a solution to this issue?
It's pretty easy, actually. You use PDO::FETCH_CLASS
and specify which class you want to instantiate for each row.
Here is an example that fetches all available rows as an array of objects of class YourClassName
.
function select($query) {
try {
$sql = $this->connect->query($query);
return $sql->fetchAll(PDO::FETCH_CLASS, YourClassName);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
Only use $sql->fetch(PDO::FETCH_ASSOC)
within the while loop, not before, as you have it.
So, like:
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// something
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.