7

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????
{
...
}
4
  • 2
    What does $row['total_rating_votes']; contain? Commented May 18, 2010 at 9:31
  • $row['total_rating_votes']; should contain NULL as no records exist in submission_ratings table. I have verified this by running the query in mysqladmin. Commented May 18, 2010 at 9:39
  • If there are no records, then $row['total_rating_votes'] is not set. Do a print_r($row). You should be checking the return value of execute, which will be the number of records found. Commented May 18, 2010 at 10:34
  • did You try empty($this->total_rating_votes)? It is used to determine whether a variable is considered to be empty. It also work for nulls. Commented Jan 18, 2012 at 15:47

3 Answers 3

15

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.
Sign up to request clarification or add additional context in comments.

Comments

2

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.