0

I'm saving Backbone model data, which POSTs a JSON object to my save.php file. As the model data will be for my application's users, I'd like to store unique values in a MySQL table.

Currently, I'm using this method:

$values = json_decode(file_get_contents('php://input'), true);
$name = $values["name"];

$sql="INSERT INTO `users` (name) VALUES $name";

It's giving me this error

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 'John Doe' at line 1

If I pass a simple string in the query, it works the way I'd like:

$sql="INSERT INTO `users` (name) VALUES ('John Doe')";

My questions are:

  • Why is $name not a string?
  • Is this the best way to insert a JSON object into a MySQL table?

Thank you!

4
  • Always use prepared/parameterized queries! You may be opening yourself to SQL injection attacks, and it's likely that your value for $name is the problem anyway. Commented Jun 10, 2013 at 1:00
  • can you please try print_r($values) and share? Commented Jun 10, 2013 at 1:01
  • print_r($values) yields: Array ( [name] => John Doe ) Commented Jun 10, 2013 at 1:03
  • I'm not sure how to use prepared/parameterized queries. I'll look into it. Commented Jun 10, 2013 at 1:04

1 Answer 1

1

JSON is just a representation of your data : once decoded $values["name"] contains a string with your value, John Doe. This means that, as is, your request expands to

$sql="INSERT INTO `users` (name) VALUES John Doe";

which is both an invalid syntax and very insecure.

Use the PDO class wherever you can, something like this :

$sql = "INSERT INTO users (name) VALUES(?)";
$sth = $dbh->prepare($sql);
$sth->execute(array(
    $name
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.