Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO fetch null

Tags:

sql

php

mysql

pdo

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????
{
...
}
like image 944
Jacob Avatar asked May 18 '10 09:05

Jacob


2 Answers

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: Empty stringis converted to NULL.
  • PDO::NULL_TO_STRING: NULL is converted to an empty string.
like image 150
Mark Baker Avatar answered Sep 21 '22 21:09

Mark Baker


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 ""

Hope this helps!

like image 41
Pierre Avatar answered Sep 19 '22 21:09

Pierre