本文介绍了mysqli:它可以在一条语句中准备多个查询吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以准备一个执行多个查询的mysqli语句:

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);

以这种方式产生错误:在...中的非对象上调用成员函数bind_param()

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(); 

推荐答案

一条准备好的语句只能执行一个MySQL查询.您可以在不同的变量中准备任意数量的语句:

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 (?,?);");

然后再执行它们.如果您要确保除非两个都能够运行,否则任何一个都不会运行,那么您需要像Thomas所说的那样研究事务.

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.

此外,一个一般性的提示:在prepare()失败并且因此$stmt实际上不是准备好的语句对象时,您将获得标准错误",这是在非对象上调用成员函数".通常,这意味着您需要在prepare()语句中查找错误,而不是以后查找任何错误.

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.

这篇关于mysqli:它可以在一条语句中准备多个查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 06:54