2011-06-30 43 views
11

我不确定这个问题是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 

任何指针赞赏。

回答

32

看一看wp-includes\wp-db.php。 WPDB的更新功能的标题注释中说:

* @return int|false The number of rows updated, or false on error. 

所以,我怀疑你想找到(表明故障的一个布尔值)和0(整数表明已返回行false之间的区别)

如果使用==进行比较,则false0相等。因此,您需要使用===运算符来检查您是在处理布尔值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. 

有关===比较操作的更多信息,请参见the PHP manual

+0

很好的答案。谢谢 – wordpresrox

+0

有没有一种方法可以获得有关失败原因的更多信息,错误描述? – RaffAl

+0

@Bearwithit尝试检查'$ wpdb-> last_error'。这是一个公共(字符串)变量,应该有最后一个错误的描述。 –

相关问题