問題描述
我正在 PHP 中運行一個腳本,該腳本使用循環(huán)為 MySQL 創(chuàng)建一個字符串查詢.
I am running a script in PHP that uisng a loop creates a string query for MySQL.
執(zhí)行腳本后出現(xiàn)以下錯誤:
After executing the script I get the following error:
您的 SQL 語法有錯誤;請查看手冊對應(yīng)于您的 MySQL 服務(wù)器版本以使用正確的語法'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;
當(dāng)我將其復(fù)制并粘貼到 phpmyadmin 中時,它顯然可以毫無問題地執(zhí)行.
When I copy and paste it into phpmyadmin, it obviously gets executed without any problem.
有什么想法嗎?
這是PHP代碼:
有一個看起來像這樣的數(shù)組:
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;
";
}
mysqli_query($connection,$query) or die(mysqli_error($connection)."<br/>$query");
謝謝!
推薦答案
mysqli 允許使用 mysqli_multiple_query 函數(shù)進行多次查詢,如下所示:
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
", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------
");
}
} while (mysqli_next_result($link));
}
請注意,每次查詢后都需要使用分號.
note that you need to use semicolon after each query.
這篇關(guān)于Mysqli 不允許多個查詢?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!