PHP - PDO - How to fetch multiple rows with only one query?

You need modify query to

SELECT * FROM users WHERE ID IN(1,4,17);

and use fetchAll() method which returns all records instead of one.

If you don't want to use fetchAll(); then you need use fetch() in loop and you need still modify query.

while ($user = $result->fetch(PDO::FETCH_ASSOC)) {
  print_r($user);
}

Notice: you use prepared statements without parameters.


you should use it like this

$sth = $dbh->prepare('SELECT * FROM users WHERE ID IN(?,?,?)');
    if($sth->execute([1,2,3])) {
        //1,2,3 is the value to be send
        if($sth->rowCount() > 0) {
            while($result = $sth->fetchObject()) {
               print_r($result);
            }
        } else {
            echo 'there are no result';
        }
    } else {
        echo 'there error in the query';
}

there are alot of ways to do this thing but it's just the basics prepare -> execute -> fetch data

Tags:

Database

Php

Pdo