Ye Myat Aung
Ye Myat Aung

Reputation: 1853

Couldn't insert data in MySql with PHP

Here's my insert query.

$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'])";

The values passing to the query seem correct (Checked by echo-ing all the values). But I got the following error.

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

Please help?

Upvotes: 1

Views: 142

Answers (3)

Berry Langerak
Berry Langerak

Reputation: 18859

Do yourself a favour and at the very least escape the values to secure the data. Concatenate the values into the query:

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

Upvotes: 2

Jon Skarpeteig
Jon Skarpeteig

Reputation: 4128

To have PHP parse your array keys correctly you can encapsulate them with {} like this:

$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']})";

Upvotes: 2

BlueEel
BlueEel

Reputation: 359

try this:

$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']."')";

Upvotes: 1

Related Questions