I have the following problem. I have a string, which contains time and date as follows: dd/MM/yy hh:mm:ss This I have in PHP. And then I have a MySQL database, which has a column of a datetime format, where I need to insert this value. Obviously the problem is, that the format is different, so instead of the actual date, it results in a field "0000-00-00 00:00:00".
Could you please help me with converting this string and then inserting it properly into MySQL? For the MySQL I use the standard INSERT INTO command.
From the DATETIME
documentation:
MySQL retrieves and displays
DATETIME
values inYYYY-MM-DD HH:MM:SS
format.
I'd use PHP's DateTime class and DateTime::createFromFormat()
method, and convert the data into a MySQL-compatible date string, like so:
$date = DateTime::createFromFormat('d/m/Y H:i:s', $yourDateString);
$dateToBeInserted = $date->format('Y-m-d H:i:s');
Write a function to convert date,
function sqldate($date)
{
$sql_date = date('Y-m-d H:i:s',strtotime($date));
return $sql_date;
}
And your query look like,
$query = "INSERT INTO tableName (dateColumn) VALUES('".sqldate($date)."') ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With