2

我想更新我的数据,我使用它但它不会更新我的数据,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());
4

2 回答 2

0

你永远不应该使用它mysqli::multi_query()来执行你的 SQL,因为这个函数不支持参数绑定。您必须使用准备好的语句分别执行这两个查询。如果您不打算将任何数据绑定到您的 SQL,那么您可以将其减少一行并mysqli::query()改为使用。

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

<?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();
于 2020-12-24T16:28:39.423 回答
-1

最好的方法是使用 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());
?>
于 2018-08-20T10:18:27.337 回答