php mysqli:它可以在一个语句中准备多个查询吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11632902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysqli: can it prepare multiple queries in one statement?
提问by Donovant
I would like to know if i can prepare one mysqli statement that executes multiple queries:
我想知道我是否可以准备一个执行多个查询的 mysqli 语句:
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...
这样它就会出错:在非对象上调用成员函数 bind_param() ......
$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();
回答by octern
A prepared statement can only execute one MySQL query. You can prepare as many statements as you want in different variables:
一个准备好的语句只能执行一个 MySQL 查询。您可以在不同的变量中准备任意数量的语句:
$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.
然后稍后执行它们。如果您想确保除非两者都能够运行,否则任何一个都不会运行,那么您需要调查事务,就像 Thomas 所说的那样。
Also, a general tip: "call to member function on a non-object" is the standard error you get when prepare()fails and so $stmtisn't actually a prepared statement object. It usually means you need to look for an error in your prepare()statement rather than anything later.
此外,一般提示:“调用非对象上的成员函数”是prepare()失败时出现的标准错误,因此$stmt实际上不是准备好的语句对象。这通常意味着您需要在prepare()语句中查找错误,而不是稍后查找任何错误。
回答by Thomas
No, a single call to the mysqli prepare()function cannot prepare multiple queries at once. You can, however, prepare more than one query for execution by using different variables. The documentation for this function is available here.
不,对 mysqliprepare()函数的一次调用不能一次准备多个查询。但是,您可以使用不同的变量来准备多个查询以供执行。此功能的文档可在此处获得。
It also looks like you are trying to setup a transaction, which is a different question than you asked. If that's what you really want to know, then you'll need to provide more information about your database setup and probably more specifics about the use case you are trying to solve.
看起来您也正在尝试设置交易,这与您提出的问题不同。如果那是您真正想知道的,那么您需要提供有关数据库设置的更多信息,可能还需要提供有关您要解决的用例的更多细节。

