我正在尝试运行以下命令。
<?php
$db = mysqli_connect("localhost","user","pw") or die("Database error");
mysqli_select_db($db, "database");
$agtid = $_POST['level'];
$sql = sprintf("call agent_hier(%d)", $agtid);
$result = mysqli_query($db, $sql) or exit(mysqli_error($db));
if ($result) {
echo "<table border='1'>
<tr><th>id</th>
<th>name</th>
<th>parent_id</th>
<th>parent_name</th>
<th>level</th>
<th>email</th></tr>";
while ($row = mysqli_fetch_assoc($result))
{
$aid = $row["id"];
$sql2 = "SELECT * FROM members WHERE MEMNO = '$aid'";
$result2 = mysqli_query($db,$sql2) or exit(mysqli_error($db));
while ($newArray = mysqli_fetch_array($result2)) {
$fname = $newArray['FNAME'];
$lname = $newArray['LNAME'];
$mi = $newArray['MI'];
$address = $newArray['ADDRESS'];
$city = $newArray['CITY'];
$state = $newArray['STATE'];
$zip = $newArray['ZIP'];
$kdate = $newArray['KDATE'];
$date = abs(strtotime(date('m/d/Y')) - strtotime(date($kdate))) / (60 * 60 * 24);
}
echo sprintf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$row["id"],$row["name"],
$row["parent_id"],$row["parent_name"],
$row["level"],$row["email"]);
}
echo "</table>";
}
mysqli_free_result($result);
mysqli_close($db);
?>
如果我删除以下行:
$aid = $row["agent_id"];
到...
$date = abs(strtotime(date('m/d/Y')) - strtotime(date($kdate))) / (60 * 60 * 24);
}
一切都会顺利进行。如果没有,我会收到以下错误:
Commands out of sync; you can't run this command now
在研究中,我认为这可能是由于多个 MySQLi 查询同时运行,其中使用 mysqli_multi_query
但对于 the guide 中的所有样本和一般数据似乎不适用。
有什么想法吗?
最佳答案
MySQL 客户端不允许您执行仍需要从正在进行的查询中获取行的新查询。请参阅Commands out of sync有关常见错误的 MySQL 文档。
您可以使用mysqli_store_result()
从外部查询中预取所有行。这会将它们缓冲在 MySQL 客户端中,因此从服务器的角度来看,您的应用程序已获取完整的结果集。然后,即使在从现在缓冲的外部结果集中获取行的循环中,您也可以执行更多查询。
或者你mysqli_result::fetch_all()
它以 PHP 数组的形式返回完整的结果集,然后您可以循环该数组。
调用存储过程是一种特殊情况,因为存储过程有可能返回多个结果集,每个结果集可能有自己的行集。这就是为什么 @a1ex07 的答案提到使用 mysqli_multi_query() 并循环直到 mysqli_next_result() 不再有结果集。这是满足 MySQL 协议(protocol)所必需的,即使在您的情况下您的存储过程只有一个结果集。
<小时/>PS:顺便说一句,我看到您正在执行嵌套查询,因为您有代表层次结构的数据。您可能需要考虑以不同的方式存储数据,以便更轻松地查询它。我做了一个关于这个问题的演讲,标题为Models for Hierarchical Data with SQL and PHP 。我还在我的书 SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming 的一章中介绍了这个主题。 .
<小时/>以下是如何在 CodeIgnitor 3.0.3 中实现 mysqli_next_result()
:
在system/database/drivers/mysqli/mysqli_driver.php
第262行更改
protected function _execute($sql)
{
return $this->conn_id->query($this->_prep_query($sql));
}
到此
protected function _execute($sql)
{
$results = $this->conn_id->query($this->_prep_query($sql));
@mysqli_next_result($this->conn_id); // Fix 'command out of sync' error
return $results;
}
自 2.x 以来,这一直是一个问题。我刚刚更新到 3.x,必须将此 hack 复制到新版本。
关于php - 为什么 mysqli 给出 "Commands out of sync"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254295/