Multiple Queries in a Single mysqli Statement
Can you prepare a single mysqli statement that executes multiple queries?
Question:
Is it possible to construct a single mysqli statement that executes multiple queries? For instance:
<code class="php">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...");</code>
Attempting such a construction results in the error, "Call to a member function bind_param() on a non-object in..."
<code class="php">$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(); </code>
Answer:
A prepared statement can execute only a single MySQL query. You can, however, prepare multiple statements in separate variables:
<code class="php">$stmtUser = $sql->prepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?)"); $stmtProc = $sql->prepare("INSERT INTO process (id_user, idp) VALUES (?,?);");</code>
These statements can be executed subsequently. If you need to ensure that both queries are executed successfully, consider using transactions.
Remember, a "call to member function on a non-object" error typically indicates a failure in the prepare() statement, rather than issues with subsequent code.
The above is the detailed content of Can You Execute Multiple Queries in a Single mysqli Statement?. For more information, please follow other related articles on the PHP Chinese website!