Madzgo
Madzgo

Reputation: 33

Error when inserting data into MySQL database with PHP

I get the following 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 '16:45:40, 2012-12-18 16:45:40, Renovated Stone house in Perast, first line, 2012' at line 1

This is the SQL query where the problem is

$sql =  "INSERT INTO `wp_posts` (`post_author`, `post_date`, `post_date_gmt`, `post_title`, `post_modified`, `post_modified_gmt`, `xml_id`)";
$sql .= " VALUES ({$postAuthor}, {$postDate}, {$postDate}, {$title}, {$postModified}, {$postModified}, {$xmlId});";

Upvotes: 0

Views: 732

Answers (3)

Miqdad Ali
Miqdad Ali

Reputation: 6147

It should work

$sql =  "INSERT INTO `wp_posts` (`post_author`, `post_date`, `post_date_gmt`, `post_title`, `post_modified`, `post_modified_gmt`, `xml_id`)";
$sql .= " VALUES ('$postAuthor', '$postDate', '$postDate', '$title', '$postModified', '$postModified', '$xmlId')";

Upvotes: 1

Orel Eraki
Orel Eraki

Reputation: 12196

This line:

$sql .= " VALUES ({$postAuthor}, {$postDate}, {$postDate}, {$title}, {$postModified}, {$postModified}, {$xmlId});";

Should be:

$sql .= " VALUES ('$postAuthor', '$postDate', '$postDate', '$title', '$postModified', '$postModified', '$xmlId')";

Remove the wrapped: ', where the column type isn't a varchar.

Also, you must validate you're escaping the special characters inside the variables. mysql_real_escape_string

Upvotes: 3

Yogu
Yogu

Reputation: 9445

The values have to be enclosed in quotation marks, and you have to make sure that there are no quotation marks in the values.

The best way to do this is using prepared statements, e.g. with the PHP Data Objects.

Upvotes: 3

Related Questions