$ wpdb - 失败后返回什么?

Chi*_*hin 11 php mysql wordpress ezsql

我不确定这个问题是否特定于WordPress或者与mySQL有关.我试图找出如果与数据库的事务失败将返回什么.在以下场景中,我正在更新一行.如果没有更改任何值,则返回false.如果进行了更改,则返回true.如何判断交易是否失败?

$result = $wpdb->update($this->table_name, $dbfields, $where);
if($result == false)//do fail - this is not really a fail!
if($result == true)//do success
Run Code Online (Sandbox Code Playgroud)

任何指针赞赏.

Mat*_*son 37

看看吧wp-includes\wp-db.php.wpdb更新函数的标题注释说:

 * @return int|false The number of rows updated, or false on error.
Run Code Online (Sandbox Code Playgroud)

所以,我怀疑你想要找到false(表示失败的布尔值)和0(表示没有返回行的整数)之间的区别.

如果比较使用==,false并且0相等.因此,您需要使用===运算符来检查您是在处理布尔值false还是整数0.

所以,试试这些:

if ($result === false) // Fail -- the "===" operator compares type as well as value
if ($result === 0) // Success, but no rows were updated
if ($result > 0) // Success, and updates were done. $result is the number of affected rows.
Run Code Online (Sandbox Code Playgroud)

有关===比较运算符的更多信息,请参阅PHP手册.