Mysqli不允许多个查询? [英] Mysqli doesn't allow multiple queries?
问题描述
我正在PHP中运行一个脚本,该脚本会在循环中创建MySQL的字符串查询.
I am running a script in PHP that uisng a loop creates a string query for MySQL.
执行脚本后,出现以下错误:
After executing the script I get the following error:
您的SQL语法有误;请查看手册 对应于您的MySQL服务器版本以使用正确的语法 靠近"UPDATE BANNERS SET pos = 1 WHERE BID = 5;更新横幅集 pos = 2 WHERE BID = 1'在第2行"
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE BANNERS SET pos=1 WHERE BID=5; UPDATE BANNERS SET pos=2 WHERE BID=1' at line 2"
错误发生后,我立即回显查询,它看起来像这样:
right after the error I echo the query and it looks like this:
UPDATE BANNERS SET pos=0 WHERE BID=6;
UPDATE BANNERS SET pos=1 WHERE BID=5;
UPDATE BANNERS SET pos=2 WHERE BID=1;
当我将其复制并粘贴到phpmyadmin中时,它显然可以执行而没有任何问题.
When I copy and paste it into phpmyadmin, it obviously gets executed without any problem.
有什么想法吗?
这是PHP代码:
有一个看起来像这样的数组:
There is an array that looks like this:
$order[0] = 'tr_6';
$order[1] = 'tr_5';
$order[2] = 'tr_1';
$query = "";
foreach($order as $pos => $value){
$idvalue = str_replace('tr_','',$value);
$query .= "UPDATE BANNERS SET pos=$pos WHERE BID=$idvalue;\n";
}
mysqli_query($connection,$query) or die(mysqli_error($connection)."<br/>$query");
谢谢!
推荐答案
mysqli允许使用mysqli_multiple_query函数的多个查询,如下所示:
mysqli allow multiple queries with mysqli_multiple_query function like this:
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
请注意,每个查询后都需要使用分号.
note that you need to use semicolon after each query.
这篇关于Mysqli不允许多个查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!