0
$data = $mysqli->prepare("SELECT amount FROM items WHERE id=:id");
echo 'forward1';
if(!$data->execute(array(':id' => $id)))
    die("error executing".$data->error);
echo '2';
$row = $data->fetch_object();
die('Losing my mind'.$row->amount);

这只会回显“forward1”,而不是“error execution ...”或“2”。它适用于 *$mysqli->query"。如果我在查询中为 :id 添加引号 '',它将回显“forward1error execution”。

4

2 回答 2

1

首先,确保您了解准备好的语句语法和工作模型。

如:

$data = $mysqli->prepare("SELECT amount FROM items WHERE id=(?)");
            // THIS ^^ actually "prepares" an object to be used in the statement
$data->bind_param("i",$id)
            // ...then you "bind" the parameter for your statement as "i"(nteger)
echo 'forward1';
if(!$data->execute())  // And now you simply run it, with no other args
    die("error executing".$data->error);
echo '2';
$row = $data->fetch_object();
die('Loosing my mind'.$row->amount);

我建议虽然使用更像

$data->execute() or die("error executing".$data->error);

准备好的语句的主要步骤是: 1. 准备带有一些占位符值的查询;2.将所需数量的值“绑定”到查询中;3. 执行!

通过如此简单的查询,我看不出为什么这与您的情况相关。我还假设您实际上需要它来做更大的事情。如果我误解了您的观点或代码示例,请告诉我。

哦,还有..玩得开心!:-)

于 2012-04-01T21:58:15.833 回答
0

打开你的错误报告。

execute在准备失败后访问 mysqli::statement 上的方法会出现致命错误。$data === false在调用之前检查是否execute

错误信息:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':id' at line 1

请参阅此答案以了解触发此错误的原因:MYSQLI::prepare() ,使用占位符时出错 :something

请参阅PHP 手册了解如何使用 mysqli,或改用PDO

于 2012-04-01T21:31:07.713 回答