开发者

MySQL return 0 if nothing found

开发者 https://www.devze.com 2022-12-22 10:03 出处:网络
$query = \"SELECT field1, field2FROM table 开发者_Python百科WHERE id IN (1, 2, 3, 4, 5)\" $result = mysql_query($query);
$query = "SELECT field1, field2  FROM table 开发者_Python百科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?


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;
}


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);

0

精彩评论

暂无评论...
验证码 换一张
取 消