Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Łukasz Czuliński
Łukasz Czuliński
8,646 Points

Prepared statement only returning 1 array (should be more).

I've run into a problem while learning about prepared statements.

When I run this:

try{
    $conn = new PDO('mysql:host=localhost;dbname=adfm', $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare('SELECT*FROM users WHERE location = :place');
    $stmt->bindParam('place', $location, PDO::PARAM_STR);
    $stmt->execute();

    while ($row = $stmt->fetch()) {
        print_r($stmt->fetch());  
    }

} catch(PDOException $e){
    echo 'ERROR: ' . $e->getMessage();
}

The above code only returns one array. But when I do the identical query in my MySQL client like:

SELECT*FROM users WHERE location = 'Kuala Lumpur';

It returns all pertaining rows/arrays correctly. Am I doing something wrong in the prepared statement?

1 Answer

Łukasz Czuliński
Łukasz Czuliński
8,646 Points

Worked it out.

This statement was causing the problems:

    while ($row = $stmt->fetch()) {
        print_r($stmt->fetch());  
    }

Not sure how I ended up with that since it makes no sense.

I corrected it to:

    while ($row = $stmt->fetch()) {
        print_r($row);  
    }