简体   繁体   中英

Date saves to mysql database as 0000-00-00

I have this code snipet here:

    // Insert data into mysql 
     $data = "'".date('Y-m-d', strtotime(str_replace('-', '/', $data3)))."'";
     echo $data;
     $sql="INSERT INTO assets(dateOfPurchase) VALUES ('$data')";
     $result=mysql_query($sql);

I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2015-10-11'

Kindly help me sort it out.

Your immediate problem is that you have the single quotes appearing twice, once in the definition of $date , once in the query. You only need to include them once:

 $data = "'".date('Y-m-d', strtotime(str_replace('-', '/',        $data3)))."'";
echo $data;
 $sql="INSERT INTO assets(dateOfPurchase) VALUES ($data)";
 $result=mysql_query($sql);

Your more serious problems are:

  • You are using "mysql_" functions, which are no longer supported.
  • You should not be putting parameters directly into query strings. You should be using parameterized queries.

That's because you are adding extra quotes. Use it like this:

$data = date('Y-m-d', strtotime(str_replace('-', '/',        $data3)));

$sql = "INSERT INTO assets(dateOfPurchase) VALUES ('$data')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM