Tural Ali
Tural Ali

Reputation: 23240

Check db table field (datetime) if it's empty or not

After successful user registration my MySQL db table puts 0000-00-00 00:00:00 into lastlogin_date and lastlogout_date fields by default. type of both fields is datetime. In my php code i'm checking if user enters to the site for the first time

$lastlogin = $db->query("SELECT `lastlogin_date` FROM `users` WHERE `id`='$_SESSION[id]'");
    $row = $lastlogin->fetch_array(MYSQLI_BOTH);
    $lastlogin=$row['lastlogin_date'];
    if(empty($lastlogin))
    { do something} 

But, seems, empty doesnt work in this case. how to check if the lastlogin_date field is empty or not? if($lastlogin=='0000-00-00 00:00:00')??

Upvotes: 2

Views: 4808

Answers (1)

Vincent Savard
Vincent Savard

Reputation: 35927

0000-00-00 00:00:00 is a value. If you don't want to put any value, you should store NULL, which would make much more sense. NULL is the lack of value.

That being said, I think the best way is to select a boolean instead of your column :

-- (lastlogin_date is NULL) if you change your table structure
SELECT (lastlogin_date = '0000-00-00 00:00:00') as has_logged_in
  FROM users
 WHERE id = ?;

When you fetch your query, you can use $row['has_logged_in'], which is a boolean.

Upvotes: 6

Related Questions