准备好的语句何时会失败? [英] When does a prepared statement fail?

查看:106
本文介绍了准备好的语句何时会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在弄乱PHP中的MySQLi对象,并习惯于在执行语句之前准备语句.

I've been messing around with the MySQLi object in PHP, and was getting used to preparing statements before executing them.

到目前为止,我主要从事以下工作:

Thus far I've mostly been doing the following :

if($stmt = $mysqli->prepare($sql) == false){
    return $mysqli->error;
}

哪个失败了,总是告诉我我的SQL本质上是错误的.

Which, when it failed, has always told me that my SQL was wrong basically.

假设以下内容:

  • 已进行检查以确保MySQL连通性
  • SQL是正确的,即使它返回0行.
  • 所有相关表都存在.
  • A check has been done to ensure MySQL connectivity
  • The SQL is correct, even if it returns 0 rows.
  • All relevant tables exist.

在什么情况下准备好的语句可能会失败?我问,主要是想知道if($stmt = $mysqli->prepare($sql))是否有用,还是我只是在浪费代码行?

Under what circumstances could a prepared statement fail? I ask, mainly wondering if there is any point to if($stmt = $mysqli->prepare($sql)), or am I just wasting lines of code?

推荐答案

有效查询失败的方式有很多:

There are many ways a valid query can fail:

  • 您对表的特权可能会被撤消.

  • Your privileges to the tables could be revoked.

可以在无效上下文中使用参数占位符格式化正确的SQL查询.

The correct SQL query could be formatted with parameter placeholders in invalid contexts.

查询可能会根据服务器设置而引发错误,例如被零除会返回NULL,但是有人可以启用

The query could throw an error depending on server settings, for example division by zero returns NULL but someone could enable the SQL mode globally on the server to make division by zero throw an error. There are other cases too, where server settings can alter the meaning of a valid SQL query.

您说这些表存在,但是任何表都可以删除或重命名.另外,列可能会更改,因此您先前有效的SQL查询将不再找到其命名的列,或尝试以无效的方式使用它们.

You say that the tables exist, but any table can be dropped or renamed. Also, columns may be altered, so your previously valid SQL query no longer finds the columns it names, or attempts to use them in invalid ways.

连接可能会意外终止.

因此,当您准备执行查询时,您确实需要检测并响应错误.

So you do need to detect and respond to errors both when you prepare and when you execute a query.

想像一个简单的文件打开功能,例如 fopen().如果您拼写错误的文件名,或者在尝试打开文件之前就删除了文件,或者有人更改了文件特权,以致您无法使用指定的访问模式来读取文件,则可能会出错.这意味着您需要在 fopen()调用之后检查是否成功.

Think of an analogy to a simple file-opening function like fopen(). You could have errors if you misspell the filename, or if the file is deleted right before you try to open it, or if someone changes the file privileges so you can't read it with the access mode you specified. This means you need to check for success after every fopen() call.

如果将mysqli配置为引发异常,则可以减少错误检查代码.参见 http://www.php.net/manual/en/mysqli-driver.report-mode.php

You may reduce the error-checking code if you configure mysqli to throw exceptions. See http://www.php.net/manual/en/mysqli-driver.report-mode.php

这篇关于准备好的语句何时会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆