Ab Hamid Sajid
Ab Hamid Sajid

Reputation: 19

Unable to save the exact timestamp from form

I'm trying to save events into my table that contain date_start and date_end timestamps. From another PHP page, I get four inputs: two date inputs and two time inputs. I'm trying to insert these values but I keep getting the following value on inserting it:

0000-00-00 00:00:00

Here's my script:

$rep=$bdd->query('SELECT * FROM association WHERE nom="'.$_SESSION['usertag'].'"');
$data=$rep->fetch();
$debut="\'".$_POST['date_start']." ".$_POST['time_start'].":00\'";
$fin="\'".$_POST['date_end']." ".$_POST['time_end'].":00\'";
$debut=date('Y-m-d H:i:s');
$fin=date('Y-m-d H:i:s');
$timestamp_debut =strtotime($debut);
$timestamp_fin = strtotime($fin);
$req=$bdd->query('INSERT into evenement values (NULL,'.$_POST['name'].','.$_POST['content'].',\''.$timestamp_debut.'\',\''.$timestamp_fin.'\','.$data['id'].')');

Upvotes: 0

Views: 94

Answers (1)

showdev
showdev

Reputation: 29168

PHP's strtotime() outputs a Unix timestamp. If your database column type is DATETIME, a Unix timestamp is not the correct format. You can just insert the formatted date() string.

For example:

strtotime(date('Y-m-d H:i:s'))

1562117846

date('Y-m-d H:i:s')

2019-07-02 21:36:40

For MySQL:

MySQL recognizes DATETIME and TIMESTAMP values ... [a]s a string in either 'YYYY-MM-DD hh:mm:ss' or 'YY-MM-DD hh:mm:ss' format. A "relaxed" syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

String and Numeric Literals in Date and Time Context


However, it seems that you're using the current timestamp when you might want to use the values posted from your form. PHP's date() uses "the current time if no timestamp is given".

If you want to use your posted values instead, you can indeed use strtotime() to convert them to Unix timestamps and then date() to format them.

$date = '2019-07-02';
$time = '15:28';

date('Y-m-d H:i:s',strtotime($date.' '.$time));

2019-07-02 15:28:00

Alternatively, I might recommend using PHP's DateTime class:

$date = '2019-07-02';
$time = '15:28';

$datetime = new Datetime($date.' '.$time);
echo $datetime->format('Y-m-d H:i:s');

2019-07-02 15:28:00

Upvotes: 1

Related Questions