简体   繁体   中英

php mysqli_multi_query() stops inserting after first query

I'm trying to insert multiple rows into the same table using a mysqli_multi_query function, but it only executes the first query. I have tried adding the values to the end of the first query separated by a comma as well, but nothing seems to work. Any suggestions?

I've switched to prepared statements but still only the first result is inserted. Am I missing something?

$DBConnect = mysqli_connect("localhost", "root", "", "getpressed");

if ($DBConnect->connect_error) {
die("Connection failed: " . $DBConnect->connect_error);

}

$stmt = $DBConnect->prepare("INSERT INTO orderdetails (orderID, productID, quantity) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $orderID, $productID, $quantity);

$orderID = $orderID;
$productID = 1;
$quantity = $sportShirtQuantity;
$stmt->execute();

$orderID = $orderID;
$productID = 2;
$quantity = $sportCoatQuantity;
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$DBConnect->close();

I had a primary key index on orderID that wouldn't allow me to insert multiple rows with the same orderID. I'm an idiot. Thank you all for your help. It does work much better with prepared statements as suggested by tadman.

I changed your code a bit

$mysqli = new mysqli("localhost", "root", "", "getpressed");

if ($mysqli->connect_errno) {
    die("Connection failed: " . $mysqli->connect_error);
}

$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."');";

if ($mysqli->multi_query($sql))) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());

I also highly recommend you to use PDO prepared statements in future.

Remove the semicolon off of the last statement. The documentation notes that the semicolon for this method is used to concatenate statements, not end them.

Read the documentation here: Link

$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM