检查数据库表字段(日期时间)是否为空

时间:2022-09-15 16:39:00

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

用户注册成功后,我的MySQL db表默认将0000-00-00 00:00:00放入lastlogin_date和lastlogout_date字段。这两个字段的类型是datetime。在我的PHP代码中,我正在检查用户是否第一次进入该网站

$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')??

但是,似乎空在这种情况下不起作用。如何检查lastlogin_date字段是否为空? if($ lastlogin =='0000-00-00 00:00:00')??

1 个解决方案

#1


6  

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.

0000-00-00 00:00:00是一个值。如果你不想放任何值,你应该存储NULL,这会更有意义。 NULL是缺乏价值的。

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.

当您获取查询时,可以使用$ row ['has_logged_in'],这是一个布尔值。

#1


6  

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.

0000-00-00 00:00:00是一个值。如果你不想放任何值,你应该存储NULL,这会更有意义。 NULL是缺乏价值的。

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.

当您获取查询时,可以使用$ row ['has_logged_in'],这是一个布尔值。