1

Can't believe there are no questions like this... Must be something really simple, but I spend 2 days trying to figure this one out.

I have a table and one of the coloumns has values in a JSON format. In PHP my syntax is like this (it's in a class function):

$sql = "INSERT INTO users.users (username, class, settings, email, password) VALUES ($this->username, $this->class, ".json_encode($this->settings).", $this->email, $this->hashpwd);";
        $STH = $DBH->prepare($sql);
        $STH->execute();

However this one of course breaks because JSON format contains commas and these commas are also separating the Insert values, so it breaks the query. And escape functions (like PDO->quote or mysqli_real_escape_string) don't escape commas either.

Error I am getting is of course:

...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 
'"usersetting1":"value","usersetting2":"value"}, email@interwebz.net, 712985cc'...

So is there any way to do this or do I have to use some kind of alt syntax for the query?

Megakoresh
  • 746
  • 1
  • 11
  • 30

1 Answers1

2

Try this:

$sql = "INSERT INTO users.users (username, class, settings, email, password) VALUES (:username, :class, :json, :email, :password);";
    $STH = $DBH->prepare($sql);
    $STH->bindParam(':username', $this->username);
    $STH->bindParam(':class', $this->class);
    $STH->bindParam(':json', json_encode($this->settings));
    $STH->bindParam(':email', $this->email);
    $STH->bindParam(':password', $this->hashpwd);
    $STH->execute();
AlexL
  • 1,699
  • 12
  • 20
  • Worked perfectly, thanks. So In that sense binding parameters is the only way to do this? – Megakoresh Oct 26 '14 at 16:37
  • It is the recommended, safest way and saves you from SQL injection. You should always use binding parameters. – AlexL Oct 26 '14 at 17:43