我有以下代码:
<ol>
<?php
$db = mysqli_connect("host","login","pass","dbase");
$stmt = $db->prepare("SELECT id,name FROM table1 WHERE faculty=?");
$stmt->bind_param("d",$fac);
$stmt->execute();
$stmt->bind_result($id,$name);
while($stmt->fetch())
{
echo "<li>$name:<ul>";
$stmt2 = $db->prepare("SELECT mac,ip FROM table2 WHERE uid=?");
$stmt2->bind_param("d",$id);
$stmt2->execute();
$stmt2->bind_result($mac,$ip);
while($stmt2->fetch())
{
echo "<li>$mac ($ip)</li>";
}
echo "</ul></li>";
}
?>
</ol>
我收到错误Commands out of sync; you can't run this command now
。我知道我不能同时运行多个查询,但我已经读过,我可以使用$stmt->store_result()
。问题是,它对我的情况没有帮助(我试着在$stmt->execute()
之后调用它)。如何让我的代码工作?有没有可能没有将第一个查询的结果存储在数组中?
答案 0 :(得分:2)
在这种情况下,使用LEFT JOIN
的单个查询将起作用:
SELECT `t1`.`id`, `t1`.`name`, `t2`.`mac`, `t2`.`ip`
FROM `table1` AS `t1`
LEFT JOIN `table2` AS `t2`
ON `t1`.`id` = `t2`.`uid`
WHERE `t2`.`uid` = ?
如果表1中的id
为uid
,则此查询将一次性返回所有四列。