Home > Article > Backend Development > Can MySQL Prepared Statements Handle Multiple Queries at Once?
Can Multiple Queries Be Prepared in a Single mysqli Statement?
In MySQL, a prepared statement executes only a single query. While it's not possible to prepare multiple queries in a single statement, you can create separate prepared statements for each query.
Consider the following example:
$stmtUser = $sql->prepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?)"); $stmtProc = $sql->prepare("INSERT INTO process (id_user, idp) VALUES (?,?);");
Here, two prepared statements ($stmtUser and $stmtProc) have been created. You can then execute these statements as needed:
$stmtUser->execute(); $stmtProc->execute();
If you need to ensure that both queries are executed together, you can use a transaction to group them. A transaction guarantees that either both queries are executed, or none are.
Tip: A "call to member function on a non-object" error often indicates that prepare() failed. Verify the query in prepare() to resolve any issues.
The above is the detailed content of Can MySQL Prepared Statements Handle Multiple Queries at Once?. For more information, please follow other related articles on the PHP Chinese website!