【发布时间】:2014-05-12 13:41:48
【问题描述】:
你好,我有几个查询要执行,都返回独立的结果集:
select * from table;
call procedureA(par1);
call procedureB(par2);
我想在循环中执行它们以执行其他操作:
$queries = array("select * from table;", "call procedureA(par1);", "call procedureB(par2);");
foreach($queries as $query) {
$res=$db->query($query);
// do something here with the query result
someFunction($res);
}
第一条语句运行良好;在第二次迭代中,它不再声明 $res 是一个非对象:
Call to a member function ... on a non-object
除了使用mysqli_multi_query(),我还可以通过什么方式循环执行多个查询?
更新我从代码示例中删除了 $res->close();,因为它对问题具有误导性和影响力。
更新 2 - 解决方案 为了任何人的利益,这是一个完整的工作代码:
$queries = array(
"CALL procedureA(par1)"
,"CALL procedureB()"
, "Select * from tableC"
);
// Open connection
$db = new mysqli(
$config['host']
,$config['user']
,$config['pwd']
,$config['dbname']
);
foreach($queries as $query) {
if ($res instanceof mysqli_result) {
$res->free();
}
$res=$db->query($query);
// do something with the query
echo getHtmlTable($res);
// free current result
$res->free();
// free subsequent resultset (es. the one with OK/ERR sp call status)
while ($db->next_result()) {
//free each result.
$res = $db->use_result();
if ($res instanceof mysqli_result) {
$res->free();
}
}
}
【问题讨论】:
-
$r 是从哪里来的?
-
您应该在整个循环中保持流打开,或者在每次迭代时打开并关闭它。取决于您想要使用 mysql 进行的事务处理类型。由于它没有看到打开的流,是的,它会停止
-
什么是
$r?如果$r是您正在关闭的 mysql 服务器的句柄并且它不再可用 -
$r 是结果集。即使省略 ->close() 也会出错。