Skip to content
Advertisement

PHP: Trying to insert dates in Database

I want to insert all the dates between a starting and an end date into a table in my database.

I already found a code for the two dates and the dates between.

The problem now is that the dates are not inserted into my database when running the code. Only 0000-00-00 is displayed in my date table.

Also no error message occurs when running the code so I don’t know where I made a mistake. Can someone help me with this problem?

Here is my Code:

$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) 
{
  $newdate = $dt->format("Y-m-d ");

  $statement = $pdo->prepare("INSERT INTO table (date) VALUES ($newdate)");
  $statement->execute();
}

Advertisement

Answer

You forgot to enclose the date value inside the SQL with single quotes. Therefore the SQL engine is trying to treat your input as a number, but it can’t (because clearly a date is not a valid number).

But you shouldn’t include raw data into your query like that anyway. Using parameters makes it far less likely you’ll make simple syntax errors like that (as well as protecting your data from SQL injection when dealing with external data input).

$statement = $pdo->prepare("INSERT INTO table (date) VALUES (:newdate)");
$statement->bindParam(':newdate', $newdate);
$statement->execute();

See the PHP manual on using prepared statements

P.S. If your code was throwing an error due to the bad SQL, you might not see it unless you have switched on PDO exception handling when you create your connection.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement