如何同时执行多个 MySql 查询?

How to execute multiple MySql query at same time?

我想更新我的数据,我使用它但它不会更新我的数据,id 仍然是空的。那么,如何同时执行多个 SQL 查询?

$mysqli = new mysqli("a", "a", "a", "a");

if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}

$sql = "UPDATE laporan_gini SET id_provinsi='1' WHERE nama_item_vertical_variabel= 'INDONESIA'";
$sql = "UPDATE laporan_gini SET id_provinsi='61' WHERE nama_item_vertical_variabel= 'KALIMANTAN BARAT'";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());

最好的方法是使用 sql 触发器或存储过程:
https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-stored-procedures.html

您可以用其他方式 运行 在代码中:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

您永远不应使用 mysqli::multi_query() to execute your SQL because this function does not support parameter binding. You must execute both queries separately using prepared statements. If you do not intend to bind any data to your SQL then you can reduce it by one line and use mysqli::query()

如果两个查询相互依赖,那么您可以将它们包装在一个事务中(假设您的 table 引擎支持事务)。

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("a", "a", "a", "a");
$mysqli->set_charset('utf8mb4'); // always set the charset

// start transaction
$mysqli->begin_transaction();

$sql = "UPDATE laporan_gini SET id_provinsi='1' WHERE nama_item_vertical_variabel= 'INDONESIA'";
$stmt = $mysqli->prepare($sql);
$stmt->execute();

$sql = "UPDATE laporan_gini SET id_provinsi='61' WHERE nama_item_vertical_variabel= 'KALIMANTAN BARAT'";
$stmt = $mysqli->prepare($sql);
$stmt->execute();

// commit data and end transaction
$mysqli->commit();