tags:

views:

47

answers:

2
$query = "SELECT field1, field2  FROM table WHERE id IN (1, 2, 3, 4, 5)"
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);

If there is no id#3, then $array['field1'][3] returns next result (if any).

But I need it to return 0 in that case.
So that $array should contain 5 elements, even if not all were in database.

Is it possible to do this?

A: 

If you are sure about the id's you are requesting then it's perhabs the easiest to do it with PHP.

Just generate an empty array of the correct size first (not a very machine-heavy operation), then fetch all rows and immediatly put them on the right key while fetching.

Like

$array = range(0,5);
while(mysql_fetch_assoc($result)) {
  $array[$result['id']] = $result;
}
douwe
A: 

You could also use array_merge to do the same as what douwe is suggesting, i.e.

$query = "SELECT field1, field2 FROM table WHERE id IN (1, 2, 3, 4, 5)"

$result = mysql_query($query);

$array = mysql_fetch_assoc($result);

$myarray = array(0=>"");

$newarray = array_merge($myarray,$array);

Lee