Dexpras
Dexpras

Reputation: 426

Generate and insert date into MySQL database using php

I used following code to insert the yesterday date into my_table of MySQL database. It worked fine in WAMP and MAMP. But it doesn't work in my host. What would be the reason Please help...

$dt = new DateTime();

$d = date_add($dt,date_interval_create_from_date_string("-1 days"));

$date = $d->format('Y-m-d');

$import="INSERT into my_table (date) Values('$date')”;

mysql_query($import) or die(mysql_error()); 

Upvotes: 4

Views: 6953

Answers (2)

Krish R
Krish R

Reputation: 22711

Remove and use "

$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
$YesterdayDate = $date->format('Y-m-d H:i:s');

$import="INSERT into my_table (`date`) Values('$YesterdayDate')";
                                               .....^

NOTE: Use mysqli_* OR PDO functions instead of mysql_* functions(deprecated)

Upvotes: 1

Antoine Subit
Antoine Subit

Reputation: 9913

Maybe your host doesn't support the DateTime() function ...

Try with date() and strtotime() functions :

$today = time();
$yesterday = date('Y-m-d H:i:s', strtotime('-1 day', $today));

Upvotes: 4

Related Questions