0

I get an error when i try to string replace the date and save it in the mySQL db. The reason is the format of the DATE field. i have added my PHP code, and mySQL error message below.

$nowDate = str_replace('/', '-', $_POST['datenow']); 

echo $nowDate;

Output > 08-15-2012 , I am inserting this record to the database, but the MySQL database requires the format yyyy-mm-dd (2012-08-15) or else i get an error

Unable1 to run query:Incorrect date value: '08-15-2012' for column 'now_date' at row 1

3 Answers 3

6

As the error specifies, the format of the date needs to be yyyy-mm-dd.

You can format it prior to inserting it with date() and strtotime():

$nowDate = date('Y-m-d', strtotime($_POST['datenow']));
Sign up to request clarification or add additional context in comments.

Comments

3

Try this

$nowDate = date('Y-m-d',strtotime($_POST['datenow']));

Or better yet, if you are just trying to add the current date, let MySQL do it for you like this. This eliminate the need to sanitize the input data.

INSERT INTO table SET date_field = NOW();

Comments

0

So... what's the problem? You've already said you know MySQL requires a certain format, but want to use a format that's not supported. If you insist on using your 'bad' format, then investigate using STR_TO_DATE() within your insert query, or convert your PHP string into a valid MySQL date format.

1 Comment

I was just about to post this. Not sure why someone voted you down.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.