Mysqli doesn't allow multiple queries?

2020-02-02 03:50发布

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:

"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;

When I copy and paste it into phpmyadmin, it obviously gets executed without any problem.

Any Ideas?

Here is the PHP code:

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");

Thanks!

标签: php mysql mysqli
1条回答
走好不送
2楼-- · 2020-02-02 04:10

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.

查看更多
登录 后发表回答