jarjarjinx jarjarjinx - 10 months ago 14
SQL Question

How do I properly create a datetime in php using variables and insert them into my table?

I have several variables that each contain a string with a number value, here's a list of my variables and their supposed values:

$year = "2016";
$month = "4";
$day = "23";
$hour = "4";
$minute = "0";

I'm trying to use these values to create a datetime which I will insert into my table, my code so far is:

$new_date = new DateTime("".$year."-".$month."-".$date." ".$hour.":".$minute.":0");
mysqli_query($con,"INSERT INTO schedule (date) VALUES ($new_date)");

But I'm getting an error which is:
Catchable fatal error: Object of class DateTime could not be converted to string


You have to format your date object and use the string for mysql insert

PHP DateTime Format

$new_date = new DateTime("".$year."-".$month."-".$date." ".$hour.":".$minute.":0");
$formatted = $new_date->format('Y-m-d H:i:s');
mysqli_query($con,"INSERT INTO schedule (date) VALUES ($formatted)");