2010-05-18 51 views
5

如何检查列值是否为空?示例代码:PHP PDO获取null

$db = DBCxn::getCxn(); 

$sql = "SELECT exercise_id, author_id, submission, result, submission_time, total_rating_votes, total_rating_values 
FROM submissions 
LEFT OUTER JOIN submission_ratings ON submissions.exercise_id=submission_ratings.exercise_id 
WHERE id=:id"; 

$st = $db->prepare($sql); 

$st->bindParam(":id", $this->id, PDO::PARAM_INT); 

$st->execute(); 
$row = $st->fetch(); 

$this->total_rating_votes = $row['total_rating_votes']; 

if($this->total_rating_votes == null) // this doesn't seem to work even though there is no record in submission_ratings???? 
{ 
... 
} 
+2

'$ row ['total_rating_votes'];'contains? – 2010-05-18 09:31:41

+0

$ row ['total_rating_votes'];应该包含NULL,因为submission_ratings表中不存在任何记录。我通过在mysqladmin中运行查询来验证这一点。 – Jacob 2010-05-18 09:39:12

+0

如果没有记录,则未设置$ row ['total_rating_votes']。做一个print_r($ row)。您应该检查执行的返回值,这将是找到的记录数。 – 2010-05-18 10:34:17

回答

0

感谢您的所有答案。经过一些实验,这段代码解决了我的问题

$this->total_rating_votes = $row['total_rating_votes']; 

if(!isset($this->total_rating_votes)) // this is now true if this record had a NULL value in the DB!!! 
{ 
... 
} 
12

当您连接到数据库,你可以设置一些属性来控制PDO如何处理空值和空字符串时,他们是由数据库查询

PDO ::的setAttribute(PDO返回: :ATTR_ORACLE_NULLS,$选项)

其中$选项是下列之一:

  • PDO :: NULL_NATURAL:没有转换。
  • PDO :: NULL_EMPTY_STRING:空的字符串转换为NULL。
  • PDO :: NULL_TO_STRING:将NULL转换为空字符串。
2

是不是就像你想要做的事情?

foreach($row as $r){ 

if($r->total_rating_votes == null){ 

    //do something 

} 

事实上,你可能会想尝试:

if($r->total_rating_votes == ""){/*do something*/} 

因为PHP可能已经转换的空值到一个空字符串,然后它实际上不是空,它的“”

希望这帮助!