无法使用PHP在MySql中插入数据

时间:2011-05-23 11:03:42

标签: php mysql

这是我的插入查询。

$insertQuery = "INSERT INTO timeline (id_str, from_user, text, timestamp, location) VALUES ($resultsAry[$x]['id_str'], $resultsAry[$x]['from_user'], $resultsAry[$x]['text'], $datetime, $locationAry[$i]['place'])";

传递给查询的值似乎是正确的(通过回显所有值来检查)。但是我收到了以下错误。

Insert failed: 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 '['id_str'], Array['from_user'], Array['text'], 2011-05-23 18:58:27, Array['place' at line 1

请帮帮忙?

3 个答案:

答案 0 :(得分:2)

要让PHP正确解析数组键,可以使用{}封装它们,如下所示:

$insertQuery = "INSERT INTO timeline (id_str, from_user, text, timestamp, location) VALUES ({$resultsAry[$x]['id_str']}, {$resultsAry[$x]['from_user']}, {$resultsAry[$x]['text']}, $datetime, {$locationAry[$i]['place']})";

答案 1 :(得分:2)

帮自己一个忙,至少逃避价值以保护数据。将值连接到查询中:

$insertQuery = "
INSERT INTO timeline (
   id_str, 
   from_user,
   text,
   timestamp, 
   location
) 
VALUES (
   '" . mysql_real_escape_string( $resultsAry[$x]['id_str'] ) . "',
   '" . mysql_real_escape_string( $resultsAry[$x]['from_user'] . "',
   '" . mysql_real_escape_string( $resultsAry[$x]['text'] . "',
   '" . mysql_real_escape_string( $dateTime ) . "',
   '" . mysql_real_escape_string( $locationAry[$i]['place']) . "'
);";

echo $insertQuery;

答案 2 :(得分:1)

试试这个:

$insertQuery = "INSERT INTO timeline (id_str, from_user, text, timestamp, location) VALUES ('".$resultsAry[$x]['id_str']."', '".$resultsAry[$x]['from_user']."', '".$resultsAry[$x]['text']."', '".$datetime."', '".$locationAry[$i]['place']."')";