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

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

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.

Related

PHP MySQL date format search

I'm trying to create a query that takes the users input from a text field called $incorporation_date.
Query Idea
$sql = "SELECT * FROM companies WHERE incorporation_date LIKE '%%%%/%%/%%" . $incorporation_date . "%%%%/%%/%%'";
How would I make it so that you could use SQL to bring up the values of the submitted format you enter.
Example search 2015-06-15
Use a Date or Datetime and spare yourself of the grief that would otherwise follow were it not
drop table theGuy;
create table theGuy
(
id int not null auto_increment primary key,
fullName varchar(60) not null,
birthDate date not null
);
insert theGuy (fullName,birthDate) values ('Kim Smithers','2002-3-1'),('John Doe','2014-4-5');
select * from theGuy where birthDate>='2000-1-1' and birthDate<='2007-12-31';
select * from theGuy where birthDate between '2000-1-1' and '2007-12-31';
select *,birthDate+interval 45 DAY as BirthCertAvail from theGuy;
select *,datediff(curdate(),birthDate) as DaysAlive from theGuy;
You might find the built-in routines adequate, such as intervals, without having to rewrite them. ;)

insert query only if mysql enum value is set to 'Yes'

i amn trying to run an insert query to insert the NOW() time and date only if certian enum values in my table are set to yes.
my table has 4 columns 'form1_completed', 'form2_completed', 'form3_completed', 'form4_completed'
the columns will be yes or no.
i am using this query to try and insert the current time and date into the database, its inserting but it doesnt pay attention to the where clause and just inserts anyway, can someone please show me what im doing wrong
$query2 = "IF (SELECT * FROM `supplier_session` WHERE `form1_completed` = 'Yes' AND `form2_completed` = 'Yes' AND `form3_completed` = 'Yes' AND `form4_completed` = 'Yes') INSERT INTO `supplier_session` (`completed_date`) VALUES (NOW());
WHERE `user_IP` = '$ipaddress '";
Instead of
WHERE `form1_completed` = Yes
use
WHERE `form1_completed` = 'Yes'
I think it should be:
IF EXISTS (SELECT * FROM ...) INSERT INTO ...
EXISTS (subquery) is true when the subquery returns any rows.
Or you could do:
IF (SELECT COUNT(*) FROM ...) INSERT INTO ...

get columns default values as they are a row of a resultset

is there a way to get default values of columns as they are a row of a resultset?
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`state` tinyint(2) NOT NULL DEFAULT '22',
`pubdate` datetime NOT NULL DEFAULT '2012-01-01 00:00:00',
for instance a table like this should return this record:
id->NULL (?)
state->22
pubdate->2012-01-01 00:00:00
in practice, when some user opens edit.php?id=44 he will get the row 44 (update mode), but if he opens edit.php?id=0 (insert mode) I want that the fields contain default values as place holders
thank you in advance
There is a DEFAULT function
SELECT DEFAULT( id ) , DEFAULT( EXAMPLE ) FROM test LIMIT 1
With above query, it seems that you need to have atleast one record in the table as it returns no records otherwise. For current timestamp, it return a timestamp formatted string of 0s.
Sure, using the information_schema database (which stores all the information about your database structure), you can do something like:
SELECT
COLUMN_NAME,
COLUMN_DEFAULT
TABLE_NAME
FROM information_schema.COLUMNS
WHERE
TABLE_NAME='your_table_name'
AND TABLE_SCHEMA='your_database_name'
If you have a limited number of columns, you can collect them into a row using a construct like:
SELECT
id.defaultval AS id_default,
state.defaultval AS state_default,
pubdate.defaultval AS pubdate_default
FROM
(SELECT TABLE_NAME, COLUMN_DEFAULT AS defaultval FROM information_schema.COLUMNS WHERE TABLE_NAME='your_table' AND TABLE_SCHEMA='your_database' AND COLUMN_NAME='id') id
JOIN (SELECT COLUMN_DEFAULT AS defaultval FROM information_schema.COLUMNS WHERE TABLE_NAME='your_table' AND TABLE_SCHEMA='your_database' AND COLUMN_NAME='state') state ON id.TABLE_NAME = state.TABLE_NAME
JOIN (SELECT COLUMN_DEFAULT AS defaultval FROM information_schema.COLUMNS WHERE TABLE_NAME='your_table' AND TABLE_SCHEMA='your_database' AND COLUMN_NAME='pubdate') pubdate ON id.TABLE_NAME = pubdate.TABLE_NAME
Use DESCRIBE http://dev.mysql.com/doc/refman/5.0/en/describe.html
DESCRIBE sometable [somefield]
Here is php example for single field:
$resource = mysql_query("DESCRIBE sometable somefield");
$schema = mysql_fetch_assoc($resource);
$default = $schema['default'];
And here is the php example for few fields:
$resource = mysql_query("DESCRIBE sometable");
while ($schema = mysql_fetch_assoc($resource)) {
$default_list[$schema['Field']] = $schema['Default'];
}
I see no use for such a behavior and find it wrong.
It is not convenient to use. Imagine I want to enter my own state value. I'd have to delete default 22 first.
Even worse with date. Instead of setting current datetime, you are going to make me edit whole date. Why?
And for the id it is just impossible.
Why can't you just check the input fields and if empty - not to insert at all, letting database set these defaults
You just overthinked it, I believe.

conversion of datetime datatype to date and time datatype in php/mysql

I am a newbie. I started php coding few days back. I want to copy a "datetime" datatype in php to fields that are of "date" and "time" datatype.
I have kept the field name datetime_info for the datetime value. It exists in try1 table. date is the name of field for "date" datatype and time is the name for "time" datatype. These two exist in try2 table.
Here is what I have written.
$result = mysql_query("SELECT * FROM try1");
while ($row = mysql_fetch_array($result))
{
$result_update = mysql_query("INSERT INTO try2 (date, time) VALUES ('".$row_team['datetime_info']."', '".$row_team['datetime_info']."')");
if (!$result_update)
die('Error: ' . mysql_errno() . mysql_error());
}
The values stored in "try1" table are:
id datetime_info
1 2008-10-02 00:00:00
2 2008-10-09 00:00:00
The expected response should be the date and time stored in respective fields. However, the output is
id date time
2 0000-00-00 00:00:00
3 0000-00-00 00:00:00
Can anyone explain me why and how? I tried a lot of sites but did not find any proper explanation for this. Thank you in anticipation.
Regards,
BasicGem
First of all, you shouldn't have to use PHP to do the hard work here. MySQL is very powerful to do these kinds of tasks on it's own.
Since you are copying all rows from table try1 into try2 (but splitting the datetime column), the following should work:
INSERT INTO
`try2`
SELECT
null, DATE( `datetime_info` ), TIME( `datetime_info` )
FROM
`try1`
What this does is: for every record found in try1 insert the following values into try2:
null means use the auto_increment functionality of the id column in try2 (this is presuming the id column is indeed an auto incrementing primary key field)
DATE( `datetime_info` ) means use the DATE part of the datetime_info column of try1
TIME( `datetime_info` ) means use the TIME part of the datetime_info column of try1
Simply doing mysql_query( $sql ) where $sql is a string that represents above query should suffice then. No need to loop through any results first with PHP.
I was gonna write a PHP solution as well, but others have already done so. I would have suggested this answer.
$result = mysql_query("SELECT * FROM try1");
while ($row = mysql_fetch_array($result))
{
$split = explode(' ', $row_team['datetime_info']);
$result_update = mysql_query("INSERT INTO try2 (date, time) VALUES ('". $split[0]."', '".$split[1]."')");
if (!$result_update)
die('Error: ' . mysql_errno() . mysql_error());
}
Because your taking it into a format and pushing it to fit another one.
Just use explode() and you'll have the 2 parts you need.
list($date, $time) = explode(' ', $row_team['datetime_info']);
Field of type date stores the date information, meaning year, month and day (in that order).
time field, as you might have guessed, stores time information in format of hour:minute:second.
If you take a look at what you did, which is inserting a datetime into date field and time field respectively - MySQL doesn't recognize the format (you are passing the data in the wrong format that's expected for date or time field), hence it stores it as default date value.
You need to parse the output of datetime_info column into the date part and time part and then feed it to mysql.

Filling NULL value again on deletion or updation

I have updated certain field in my database & that field has default value as NULL. How can I again fill NULL if field is emptied or deleted. As during this updation blank value is filled in database and of course that is not NULL. Is filling NULL instead of blank value good?
Using php how can I do that? Suppose I have condition if code
if(!empty($photo))
{ $a in database;
}
But in this condition if $photo is empty it will fill blank value of $a... Let me know to fill NULL in database.
You just have to write null, and not an empty value, to your database.
You SQL query would look like this :
update your_table
set your_field = NULL
where ...
instead of :
update your_table
set your_field = ''
where ...
To switch between those two queries, you might need some condition in your PHP code, depending on how it's organized ; maybe like this :
if (empty($photo)) {
// query to set the field to NULL
}
else {
// query to update the value
}
Note that if you have no value to store for a row in your database, you might also want to just delete that row :
delete from your_table
where ...
Of course, it's up to you to determine which is the best for your application : a row with a NULL value, or no row.

Categories