Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect null column value in PHP mysqli

Tags:

php

mysql

mysqli

I have a php project that uses mysqli to query a database. Some of the columns in this database can be null. I have code that looks something like this:

$query = "...";
$result = $DB->query($query);
$row = $result->fetch_assoc();
$column = $row['mycolumn'];

If mycolumn is null, the value of $column appears to be the string, "NULL" (NOT the null value, but actually the string containing the word "NULL"). So what happens if I have columns which actually have the string "NULL" in them? How can I differentiate?

Thanks! Josh

EDIT: Upon closer inspection, it appears that the string is actually a 5-characters string. The first 4 characters are "NULL", but the last character is 0x0d, the carriage return. This makes it a lot easier to detect, although I'm still curious if there's a less hack-y way than just doing string comparison.

like image 479
joshlf Avatar asked Oct 22 '25 18:10

joshlf


2 Answers

Use an if condition to check with ===

if($row['mycolumn'] === null) {
   echo 'Real Null';
} elseif($row['mycolumn'] == '') {
   echo 'Blank';
}
like image 180
Mr. Alien Avatar answered Oct 24 '25 07:10

Mr. Alien


You are looking wrong way. Instead of trying to detect wrong NULL value you have to find out why it is wrong and correct it.

Neither Mysql nor mysqli would return a literal string 'NULL' for a null value.

So, you need to find your own code which converts NULL value to "NULL\n" string either at writing or reading. Are you using raw mysqli as $DB or it's a sort of abstraction class? If so - I'd say problem is there.

After that you can easily read NULL value with strict comparison === as suggested in other answers (though I am not sure about libmysql installations).

like image 29
Your Common Sense Avatar answered Oct 24 '25 09:10

Your Common Sense