【问题标题】:PHP Prepared statement bind_param() errorPHP Prepared 语句 bind_param() 错误
【发布时间】:2016-04-24 17:00:52
【问题描述】:

stackoverflow 上的很多人都遇到过这个问题,但我仍然无法发现错误

这是错误:

Fatal error: Call to a member function bind_param() on boolean -

这是代码行:

$insertpost = $conn->prepare("INSERT INTO posts (title,post,user,img,date,short) VALUES(?,?,?,?,NOW(),?)");
$insertpost->bind_param("sssss",$title,$comment,$user,$url,$short);

【问题讨论】:

  • $insertpost 可能是 bool false,可能是因为 prepare() 失败。
  • 您将所有字符串定义为参数类型,"sssss",查看您的参数,您似乎拥有与您定义的类型不同的类型。我至少可以看到:日期/日期时间和整数类型。这只是一个建议,它们可能是隐式转换,但为了安全起见,我通常更喜欢正确输入内容,无论它们是否有隐式转换。
  • 基本上查询 FAILED 因此变量 $insertpost 包含 false 如果您测试这种情况 ALWAYS 你不会得到这个问题。 Aso 使用$conn->error 来查看错误描述如果$insertpost === false
  • $insertpost = "插入帖子(标题、帖子、用户、img、日期、短)VALUES('".$title."','".$comment."','" .$user."','".$url."','".$date."','".$short."')";我知道它有效,因为它以前有效...

标签: php mysql sql mysqli


【解决方案1】:

更新:对于这个问题,我的原始答案完全不正确。 date 不是保留字,可以不加引号使用(感谢你们的教育,伙计们)。但是,由于未引用的保留字可能是一个常见问题,可能会导致相同的错误,因此我将把它留给未来的读者,以防万一有帮助 (https://meta.stackexchange.com/questions/37738/when-or-should-you-delete-your-incorrect-answer)。基本上:

检查您的列名。您可能有未加引号的保留字。

https://dev.mysql.com/doc/refman/5.5/en/keywords.html


原始答案:

您需要用反引号引用您的列名。您的 date 字段是保留字。

$insertpost = $conn->prepare("INSERT INTO posts (`title`,`post`,`user`,`img`,`date`,`short`) VALUES(?,?,?,?,NOW(),?)");

https://dev.mysql.com/doc/refman/5.5/en/keywords.html

【讨论】:

  • 我使用日期与它无关,在这种情况下封装也没有任何作用。
  • 虽然date 是一个不好的名称,但 MYSQL 对列进行了特殊处理,因此它实际上不再抛出错误,也不会导致查询失败。 但您不应该将其用作列名
  • 我在我的代码中的其他地方使用过它,它的工作方式是这样的 - $posts = $conn->prepare("SELECT id,title,post,short,user,img,date FROM posts ORDER BY posts.date DESC LIMIT ?"); $posts->bind_param("s",$limit);
  • 嗯,确实如此。 prepare失败是因为不封装保留字字段名时查询无效...
  • date 不是保留字,是关键字;这里有两种不同的动物。自己找dev.mysql.com/doc/refman/5.5/en/keywords.html 旁边没有(R)。让我们摆脱对此的误解;-)您甚至在答案中包含了该链接。
【解决方案2】:

在每个可能返回错误/失败状态的 mysqliPDO 函数之后,您必须测试这种可能性。

错误Fatal error: Call to a member function bind_param() on boolean 说明了一切。 $insertpost 为假,因此由于某种原因准备失败,可能是查询错误,也可能是 MYSQL Server 崩溃且无法准备语句。

所以你必须相应地编码

$insertpost = $conn->prepare("INSERT INTO posts 
                                    (title,post,user,img,date,short) 
                              VALUES(?,?,?,?,NOW(),?)");

if ( $insertpost === FALSE ) {
    // prepare failed for some reason, lets see why
    echo $conn->error;
    exit;
}
$insertpost->bind_param("sssss",$title,$comment,$user,$url,$short);

【讨论】:

  • 好的,谢谢。我添加了它并得到了错误 - “命令不同步;你现在不能运行这个命令”,所以我意识到我必须关闭我以前的连接。然后我得到了错误 - “Php mysqi bind_param 变量的数量与准备好的语句中的参数数量不匹配”所以我不得不摆脱前一个人告诉我添加的''。
猜你喜欢
  • 2018-11-17
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
相关资源
最近更新 更多