Home > Database > Mysql Tutorial > Can You Execute Multiple Queries in a Single mysqli Statement?

Can You Execute Multiple Queries in a Single mysqli Statement?

Linda Hamilton
Release: 2024-10-29 03:57:29
Original
250 people have browsed it

Can You Execute Multiple Queries in a Single mysqli Statement?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template