Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if MySQL returns null/empty?

Tags:

php

mysql

In DB I have a table with a field called fk_ownerID. By default, when I add a new table row, the fk_ownerID is empty. In Toad for MySQL, this is shown as {null}. If fk_ownerID is given a value, and I later remove this value, I set fk_ownerID = "".

Now, I have the following code:

$result = $dal->getRowByValue('tableName','id', $_POST['myID']);  // Check to see if any rows where returned if (mysql_num_rows($result) > 0) {   while ($row = mysql_fetch_array($result))   {     $ownerID = $row["fk_ownerID"];       } } 

Now the variable $ownerID should have a number, or not. But I'm unsure how to check this. Currently I'm doing this:

if ( (strlen($ownerID) == 0) || ($ownerID == '0') || ($ownerID == 'null') ) 

But I'm pretty sure only one of these tests should be necessary.

What is the best way to check if a row field is empty or null?

like image 209
Steven Avatar asked Nov 07 '09 15:11

Steven


People also ask

Is NULL or empty in MySQL?

The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value. mysql> SELECT * FROM ColumnValueNullDemo WHERE ColumnName IS NULL OR ColumnName = ' '; After executing the above query, the output obtained is.

How do I find NULL records in MySQL?

To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.

IS NULL condition returns true if the field is empty?

Checks if the value is null, empty, or contains only whitespace characters. Returns true if the string is null, empty, or only whitespace.


1 Answers

Use empty() and/or is_null()

http://www.php.net/empty http://www.php.net/is_null

Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.

like image 172
scragar Avatar answered Oct 03 '22 05:10

scragar