![](/img/trans.png)
[英]How to execute two different php prepared statements inside a foreach loop?
[英]how to execute multiple statements in loop
你好,我有几个查询要执行,所有查询都返回独立的结果集:
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
, in which way could I loop execute multiple queries? 除了使用 ,我还可以哪种方式循环执行多个查询?
更新我删除了$ res-> close(); 来自代码示例,因为它具有误导性并且对问题没有影响。
UPDATE2-解决方案就任何人而言,这是一个完整的工作代码:
$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();
}
}
}
循环运行查询没有什么特别的。
无论您是一个接一个地编写两个查询,还是循环运行它们,都没有任何区别。 因此,通常来说,循环运行的几个查询与我们所有脚本中按顺序运行的几个查询没有什么不同。
唯一可能的问题是查询本身。 说,存储过程调用总是返回至少两个结果集。 在检索所有结果集之前,无法运行其他查询。
因此,作为一种快捷的解决方案,可以添加这样的行
while ($db->next_result()) {}
在循环的底部清除查询执行后可能保留在队列中的所有结果集。
为mysqli打开错误报告,让您知道发生的所有mysql错误也非常方便。 有了它,您将在问题中添加这样的错误消息(这是“命令不同步”)。 为此,请在mysqli连接之前添加以下行:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$r->close();
应该
$res->close();
您引用的是不存在的对象($ r)。
多个查询的执行取决于服务器配置。 除了thas。 最好使用事务处理(当然,这取决于那些存储过程的影响)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.