Saturday, 16 July 2016

php - mysqli: can it prepare multiple queries in one statement?



I would like to know if i can prepare one mysqli statement that executes multiple queries:




mysqli->prepare(query1 ...1,2,3 param...; query2...4,5 param...);
or
mysqli->prepare(insert into ...1,2,3 param...; insert into...4,5 param...);
and after all
mysqli->bind_param("sssss", 1, 2, 3, 4, 5);


In that way it make error: Call to a member function bind_param() on a non-object in...



$stmt = $sql->getQueryPrepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?); INSERT INTO process (id_user, idp) VALUES (?,?);");


$stmt->bind_param("ssssss",$id, $username, $pw, $email, $id, $idp);

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

Answer



A prepared statement can only execute one MySQL query. You can prepare as many statements as you want in different variables:



$stmtUser = $sql->prepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?)");

$stmtProc = $sql->prepare("INSERT INTO process (id_user, idp) VALUES (?,?);");


And then execute them later. If you want to ensure that neither one is ever run unless both are able to run, then you need to look into transactions, like Thomas said.



Also, a general tip: "call to member function on a non-object" is the standard error you get when prepare() fails and so $stmt isn't actually a prepared statement object. It usually means you need to look for an error in your prepare() statement rather than anything later.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...