-1

How do i insert the value of date('d-m-Y h:i:s') in the clock column with DATETIME data type in MySQL table?

date_default_timezone_set("Asia/Kuala_Lumpur");
$date=date('d-m-Y h:i:s');

    $sql=mysqli_query($connection,"INSERT INTO time (clock)VALUES($date)");

i keep getting 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 '11:22:03)' at line 1

2 Answers2

2

According to the MySQL documentation, 11.3.1 The DATE, DATETIME, and TIMESTAMP Types, the DATETIME type only supports the format YYYY-MM-DD hh:mm:ss, which is equivalent to PHP formats.

  • Y-m-d h:i:s for 12 hour format.
  • Y-m-d H:i:s for 24 hour format.

Adding PM or AM will not work on MySQL.

  • i tried this `$date=date('Y-m-d h:i:s');` and this error came out `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 '09:59:30)' at line 1` – ELVIN MALIH FKI Sep 08 '19 at 14:00
0

You have multiple issues in your code:

  • MySQL's DATETIME data type expects the inserted values to be of the format %Y-%m-%d %H:%i:%s (or Y-m-d H:i:s in PHP).
  • DATETIME values must be enclosed in (single) quotes. (This is the reason for your syntax error.)

Your code should be:

date_default_timezone_set("Asia/Kuala_Lumpur");
$date = date('Y-m-d H:i:s');

$sql = $connection->query("INSERT INTO time (clock) VALUES ('{$date}')");

However - Even if the value of $date doesn't come from user input, and contains no special SQL characters, it creates "code smell", which is having variables being interpolated in SQL queries. You should start now using parameterized prepared statements. Which would be:

$stmt = $connection->prepare("INSERT INTO time (clock) VALUES (?)");
$stmt->bind_param('s', $date);
$stmt->execute();
Paul Spiegel
  • 30,925
  • 5
  • 44
  • 53
  • wow, this works great. it solved the error, Thank you so much sir. By the way, what about other values? do i need to type like `'{$date}'` as well or its just for DATETIME column? – ELVIN MALIH FKI Sep 08 '19 at 16:10
  • You could also use `'$date'` in this case. Using `{$variable}` can be considered "good practice". In some cases you need it. Eg.: `"Time: {$value}ms"` works fine. But `"Time: $valuems"` will raise an error: "*unknown variable '$valuems'*". So I tend to always use `{}`, just to be consequent and avoid bugs. – Paul Spiegel Sep 08 '19 at 16:20