Darkstar
Darkstar

Reputation: 765

Error inserting datetime into mysql datetime column using PHP

I'm trying to insert the datetime into a mysql column but I'm getting this error:

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

Here is the code I'm using to get the datetime and insert it into the "dt" datetime type column.

$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;
}

Upvotes: 2

Views: 1452

Answers (2)

Rahul
Rahul

Reputation: 77876

You are getting error cause your datetime value is not quoted as seen below and so DB engine throwing an error assuming you meant to provide more values.

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

You need to quote your datetime value using single quote like

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

Upvotes: 3

Max P.
Max P.

Reputation: 5679

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

Upvotes: 1

Related Questions