0

I'm new to PHP/SQL and very confused.

In my SQL database, I have the following values for a user:

values

In my PHP script, echoing these values gives me 0.

Query:

$query = "SELECT * FROM user WHERE email = '{$email}'";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);

I specify the email linked to the above user in the database. I get the desired row as a result (user ID 13 and these null values). Still, the code gets inside this if statement:

if (!empty($row['first_name']) && !empty($row['last_name']) && 
!empty($row['age']) && !empty($row['picture_path'])) {
    echo "inside";
}

Echoing the values themselves gave me 0 instead of null. Why? And how can I properly check for empty/null?

Thanks loads.

Community
  • 1
  • 1
LPB
  • 515
  • 4
  • 12
  • 20
  • What `DBMS` you are using? – Rigel1121 Mar 06 '15 at 03:45
  • if you want to check in php, you can use [is_null()](http://php.net/manual/en/function.is-null.php), otherwise you want to use mysql you can use [ifnull, COALESCE](http://stackoverflow.com/questions/18528468/what-is-the-difference-bewteen-ifnull-and-coalesce-in-mysql) – Emilio Gort Mar 06 '15 at 04:05
  • Doesn't !empty check, for empty and null values? – LPB Mar 06 '15 at 04:06
  • I think there's a misunderstanding. I am correctly retrieving this exact row inside my database. The problem lies when I evaluate the values and get 0 instead of null. I just edited my question to eliminate any confusion. – LPB Mar 06 '15 at 04:25
  • `$var = is_null($row['name']) ? 'Null' : $row['name']; echo $var;` – Emilio Gort Mar 06 '15 at 04:50

2 Answers2

0

You can just assign a certain string if a certain value is null using COALESCE() function. See below:

"SELECT 
       COALESCE(user_id,'null')user_id,
       COALESCE(first_name,'null')first_name,
       COALESCE(middle_name,'null')middle_name,
       COALESCE(last_name,'null')last_name,
       COALESCE(rs_status,'null')rs_status,
       COALESCE(age,'null')age,
       COALESCE(town,'null')town,
       COALESCE(phone,'null')phone,
       COALESCE(picture_path,'null')picture_path
 FROM user 
WHERE email = '{$email}'"
Rigel1121
  • 2,022
  • 1
  • 17
  • 24
0

PHP empty('0') returns true; to test for null use is_null($var).

Not intuitive but that's what it is.

vladsch
  • 606
  • 6
  • 7