AMB AMB - 5 days ago 5
PHP Question

Using PHP what is the best way to get multiple rows in one MySQL query?

Which is the best way to Get multiple rows in one MySQL query.

I have an array of IDs:

$id_array = array('34','341','342','334','344','354','3234','33234','3234','3234');


I would like to get the title associated with those id's from my mysql database.

I have two approaches:

1) example:

foreach($id_array as $id){
$query = mysqli_query($con, "SELECT title FROM content WHERE id = '$id'");
$id_db = mysqli_fetch_row($query);
echo $id_db['title'];
}


2) example:

$query = mysqli_query($con, "SELECT title FROM content WHERE id = '$id_array[1]' AND id = '$id_array[2]' AND id = '$id_array[3]' AND 'id = $id_array[4]' AND id = '$id_array[5]'");

while($result = mysqli_fetch_assoc($query)){
echo $result['title'];
}


I am working on high load site and would like to use the best solution.
The above code isn't 100% complete, it is just a raw implementation of the idea.
The array elements can be from 1 to 1k in count.

Answer

What about this solution ?

$ids = implode(',',array_map('intval',$id_array));
$query = mysqli_query($con, "SELECT title FROM content WHERE id IN ($ids)");
// ..