0

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.

jasonlam604
  • 1,456
  • 2
  • 16
  • 25

3 Answers3

2

What about this solution ?

$ids = implode(',',array_map('intval',$id_array));
$query = mysqli_query($con, "SELECT title FROM content WHERE id IN ($ids)");
// ..
Abdou Tahiri
  • 4,338
  • 5
  • 25
  • 38
1

Use mysql in array method man.

jack
  • 473
  • 5
  • 21
0

If you want get titles for ids that are in array:

$db = new mysqli('server', 'user', 'password', 'db');
$stmt = $db->prepare('select title form content where id = ?');
$stmt->bind_param('i', $i);
$stmt->bind_result($title);
$titles = array();
foreach($id_array as $a) {
  $i = $a;
  $stmt->execute();
  array_push($titles, $title);
}
train_fox
  • 1,517
  • 1
  • 12
  • 31