Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Unix Timestamp to MySQL DATETIME

This sounds silly but for the life of me I cannot figure it out. I have tried everything.

The problem is that I cannot figure out how to get my date string into my MySQL table... I've been converting to Unix first to account for variations in input format..

$_POST['date'] is in this format:19-1-2013 4:43:32

$datestr= strtotime($_POST['date']);
    echo $datestr;
    $sql = "INSERT INTO `calendar` (`date`, `title`, `event`) VALUES ('FROM_UNIXTIME(".$datestr.")', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['desc'])."')";
    $query = mysql_query($sql);

This is the most recent thing I've tried and I'm still getting all zeros in my DATETIME field.

Please, what am I doing wrong?

like image 940
I wrestled a bear once. Avatar asked Jan 08 '13 09:01

I wrestled a bear once.


People also ask

How do I select a Unix timestamp in MySQL?

We can convert MySQL date and time to Unix Timestamp with the help of function UNIX_TIMESTAMP(). The following is the query. mysql> SELECT UNIX_TIMESTAMP(STR_TO_DATE('Oct 19 2018 10:00PM', '%M %d %Y %h:%i%p'));

What is difference between timestamp and datetime in MySQL?

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.

How does MySQL store epoch time?

You want to use the TIMESTAMP data type. It's stored as an epoch value, but MySQL displays the value as 'YYYY-MM-DD HH:MM:SS'. Show activity on this post. MySql DateTime data type store the date in format 'YYYY-MM-DD HH:MM:SS' with range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.


1 Answers

remove single quotes aroung the function FROM_UNIXTIME because it will make it a value. eg

$sql = "INSERT INTO `calendar` (`date`, `title`, `event`) VALUES (FROM_UNIXTIME(".$datestr."), '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['desc'])."')";

As a sidenote, your query is vulnerable with SQL Injection, please see the article below to learn how to protect from it

  • How can I prevent SQL injection in PHP?
like image 200
John Woo Avatar answered Sep 29 '22 01:09

John Woo