I there a way I can return several rows by using a foreach in PHP ?
Example:
I want to loop into the Users
table and I have this list of Users id's
.
$users = "1,2,3";
foreach ($users as $user) {
SELECT * FROM Users where id = :user;
}
But here, I need the query the db 3 times.
Is there a way to make it in one query ?
Thanks.
using where in mysql statement you can use by single query
SELECT * FROM Users where id in ( $users);
like
SELECT * FROM Users WHERE id IN (1,2,3);
Try:
function getUsers() {
$sql = "SELECT
* FROM Users";
//echo $sql;
//$dbConn = new PDO('blah blah');
$result = $dbConn->query($sql);
//this can be output if no user exists,
$user= array();
while ($row = $result->fetch_array()) {
$users= array(
//store the id's as an array here
'id' => $row['id'],
);
array_push($user, $users);
}
}
return $user;
}
//Add prepared statements here to make prevent SQL injection