使用PHP将datetime插入mysql datetime列时出错

时间:2015-12-27 21:14:27

标签: php mysql datetime

我正在尝试将日期时间插入到mysql列中,但我收到此错误:

Error: INSERT INTO prices (priceLBTC, dt) VALUES (421.59, 2015-12-27 15:41:09) 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 '15:41:09)' at line 2

以下是我用来获取日期时间并将其插入“dt”日期时间类型列的代码。

$dateTime = new DateTime();
$date = $dateTime->format('Y-m-d H:i:s');

$sql = "INSERT INTO prices (priceLBTC, dt)
VALUES ($bitcoinPrice, $date)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

2 个答案:

答案 0 :(得分:2)

您收到错误导致您的日期时间值未被引用,如下所示,因此数据库引擎会抛出错误,假设您打算提供更多值。

INSERT INTO prices (priceLBTC, dt) VALUES (421.59, 2015-12-27 15:41:09)
                                                   ^.. Here

您需要使用单引号引用日期时间值,例如

INSERT INTO prices (priceLBTC, dt) VALUES (421.59, '2015-12-27 15:41:09')

答案 1 :(得分:1)

$sql = "INSERT INTO prices (priceLBTC, dt) VALUES (".$conn->quote($bitcoinPrice).", ".$conn->quote($date).")";