简体   繁体   English

如何正确地转义JSON字符串以与MySQL INSERT INTO命令一起使用?

[英]How to properly escape JSON string for use with MySQL INSERT INTO command?

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. 不敢相信没有像这样的问题……一定很简单,但是我花了2天的时间来弄清楚这个问题。

I have a table and one of the coloumns has values in a JSON format. 我有一张桌子,其中一列具有JSON格式的值。 In PHP my syntax is like this (it's in a class function): 在PHP中,我的语法是这样的(它在类函数中):

$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. 但是,这当然会中断,因为JSON格式包含逗号,并且这些逗号也分隔了Insert值,因此中断了查询。 And escape functions (like PDO->quote or mysqli_real_escape_string) don't escape commas either. 转义函数(例如PDO-> quote或mysqli_real_escape_string)也不会转义逗号。

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? 那么有什么方法可以做到这一点,还是我必须对查询使用某种替代语法?

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM