如何正确转义JSON字符串以用于MySQL INSERT INTO命令?

时间:2014-10-26 14:03:55

标签: php mysql json pdo

无法相信没有这样的问题......一定是非常简单的事情,但我花了两天的时间试图弄明白这一点。

我有一个表,其中一个coloumns具有JSON格式的值。在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();

然而,这当然会因为JSON格式包含逗号而中断,并且这些逗号也将Insert值分开,因此它会中断查询。并且转义函数(如PDO-> quote或mysqli_real_escape_string)也不会转义逗号。

我得到的错误当然是:

...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'...

那么有什么方法可以做到这一点,还是我必须使用某种alt语法进行查询?

1 个答案:

答案 0 :(得分:2)

试试这个:

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