PHP form won’t save date to database – PHP



I’m trying to get a form submission to automatically save the date when submitted, but I suspect that one of my variables is not right.

There are these two variables:

$timestamp = $_POST['date'];
$current_date = date('j/M/y', $timestamp);

Then I’m inserting it like so:

$query = "INSERT INTO news (`headline`, `body`, `image`, `date`)
VALUES ('$headline', '$body', '$image', $current_date);";
$result = $mysqli->query($query);

I’m wondering if the $current_date variable is my problem and how to fix it.


You don’t have single quotes around the $current_date in the query.
Might I also suggest that you

alter table news modify column date timestamp default now();

The date will then be automatic and you can remove that value from the query.
Also, you should never use that as a column name because there is a HIGH risk of MySQL being confused. Standard is last_updated_date.

I see that you’re actually getting the date from the form. Try using the single quotes around the variable and also I highly recommend changing the column name. You can call it news_date or something. I’m leaving the above post for future documentation.


note: your code indicates that your date field is a (VAR)CHAR type, which is the worst choice you could make because you cannot do sensible date calculations in SQL.


Dorm, that’s not necessarily true. He could be formatting the date a certain way or he’s paranoid that the date won’t be displayed correctly. That could also be how the code he copy/pasted was built which is one of the main reasons a developer should build their stuff from scratch. And even if it was in varchar or char, he could still do date manipulation, but it would require a conversion which would be an extra step. We really can’t assume since we don’t have the database schema.


I just checked the Db structure and it’s actually ‘timestamp’.


then $current_date = date('j/M/y', $timestamp); should not give you a correct value.


That’s (probably) correct. But, I removed the date from the insert completely. So, it’s automatic like the id now.