1

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?

2 Answers 2

3

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(); 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

2 Comments

yeah, remarked that as I posted the code ... the // something is what am missing... any points how I could go for it ?
items from $row are fetched like they are in an array. If you are doing select name from pets you would access it like: $row['name']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.