PHP PDO获取null

Jac*_*cob 6 php mysql sql pdo

如何检查列值是否为空?示例代码:

$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????
{
...
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ker 14

连接到数据库时,可以设置一些属性来控制PDO在数据库查询返回时如何处理Null和Empty Strings

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

其中$ option是以下之一:

  • PDO :: NULL_NATURAL:无转换.
  • PDO :: NULL_EMPTY_STRING:空字符串转换为NULL.
  • PDO :: NULL_TO_STRING:NULL转换为空字符串.


Jac*_*cob 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!!!
{
...
}
Run Code Online (Sandbox Code Playgroud)