简体   繁体   English

PHP PDO获取null

[英]PHP PDO fetch null

How do you check if a columns value is null? 如何检查列值是否为空? Example code: 示例代码:

$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????
{
...
}

When you connect to the database, you can set some attributes to control how PDO handles Nulls and Empty Strings when they are returned by the database query 连接到数据库时,可以设置一些属性来控制PDO在数据库查询返回时如何处理Null和Empty Strings

PDO::setAttribute (PDO::ATTR_ORACLE_NULLS, $option ) PDO :: setAttribute(PDO :: ATTR_ORACLE_NULLS,$ option)

Where $option is one of the following: 其中$ option是以下之一:

  • PDO::NULL_NATURAL: No conversion. PDO :: NULL_NATURAL:无转换。
  • PDO::NULL_EMPTY_STRING: Empty stringis converted to NULL. PDO :: NULL_EMPTY_STRING:空字符串转换为NULL。
  • PDO::NULL_TO_STRING: NULL is converted to an empty string. PDO :: NULL_TO_STRING:NULL转换为空字符串。

Isnt it something like that that you want to do? 不是你想做的事吗?

foreach($row as $r){

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

  //do something

}

Actually you might want to try: 其实你可能想尝试:

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

Because php might have converted the null value into an empty string, and then it's not actually null, it's "" 因为php可能已经将null值转换为空字符串,然后它实际上不是null,所以它是“”

Hope this helps! 希望这可以帮助!

Thanks for all of your answers. 谢谢你的所有答案。 After a bit of experimentation this code solved my problem 经过一些实验,这段代码解决了我的问题

$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!!!
{
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM