John John - 5 months ago 14
MySQL Question

Running multiple SQL queries is not working

I am trying to run multiple queries in 1 php:

$sql = "UPDATE table1 SET column='1' WHERE id='1'";
$sql.= "INSERT INTO table2(column1, column2) VALUES ('1', '2')";
if (!$mysqli->multi_query($link, $sql)) {


When I run this I get a error. Does anybody know what is wrong with my script?

Here is my full script:

<?php
$link = mysqli_connect("localhost", "root", "", "db");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "UPDATE table1 SET column='1' WHERE id='1'";
$sql.= "INSERT INTO table2(column1, column2) VALUES ('1', '2')";
if (!$mysqli->multi_query($link, $sql)) {

echo "Success";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>


Edit 1:

I get the following error:
Notice: Undefined variable: mysqli in ......../script.php on line 24

Fatal error: Call to a member function multi_query() on a non-object in ......../script.php on line 24

Answer

You need to end one statement with a semicolon and then put a space before starting the next

$sql = "UPDATE table1 SET column='1' WHERE id='1'; ";

Also, you're using the object oriented function instead of the procedural. So change it to this

if (!$mysqli_multi_query($link, $sql)) {