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

OnrS90 picture OnrS90 · Aug 12, 2015 · Viewed 15.5k times · Source

First of all, I'm new to PDO. I'm working on a small project to improve myself.

I'm using a code like this to fetch single row from my database:

    $sql = "SELECT * FROM users WHERE ID = 1";
    $sql_prepare = $db -> prepare($sql);
    $result = $db -> query($sql);
    $user = $result -> fetch(PDO::FETCH_ASSOC);

and echo any result of that row like this:

    echo $user['ID'];
    echo $user['Name'];

I need to fetch multiple rows from my database with only using one query. I dont want to query over and over again for each row that I need.

First thing that came in my mind was trying this:

    $sql = "SELECT * FROM users WHERE ID = 1 AND ID = 4 AND ID = 17";
    $sql_prepare = $db -> prepare($sql);
    $result = $db -> query($sql);
    $user = $result -> fetch(PDO::FETCH_ASSOC);

But it didnt work as expected. I researched coding forums for couple of hours but all answers were about using fetchAll method and then outputing results by using foreach loop. I dont want to strain the code by loading whole database table. I just want to load specific rows from my database by using only one query.

So my question is:

How can I fetch multiple and specific rows from my database without using fetchAll method and with only one query?

Thanks for your answers and time in advance.

Sorry if the question was asked before.

Answer

Robert picture Robert · Aug 12, 2015

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.