PHP PDO fetch null

How to check if a column value is null? Code example:

$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????
{
...
}
+5
source share
3 answers

Thanks for all your answers. After several experiments, 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!!!
{
...
}
0
source

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 :: setAttribute (PDO :: ATTR_ORACLE_NULLS, $ option)

Where $ option is one of the following:

  • PDO :: NULL_NATURAL: no conversion.
  • PDO :: NULL_EMPTY_STRING: An empty string is converted to NULL.
  • PDO :: NULL_TO_STRING: NULL is converted to an empty string.
+12

, ?

foreach($row as $r){

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

  //do something

}

:

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

Since php could convert a null value to an empty string, and then it is actually not null, it "

Hope this helps!

+2
source

All Articles