gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:50:27 24 4
gpt4 key购买 nike

不敢相信没有这样的问题...一定是非常简单的事情,但我花了 2 天试图解决这个问题。

我有一个表,其中一个列的值采用 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 格式包含逗号,并且这些逗号也分隔插入值,因此它会中断查询。并且转义函数(如 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'...

那么有什么方法可以做到这一点,或者我是否必须使用某种替代语法来进行查询?

最佳答案

试试这个:

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

关于php - 如何正确转义 JSON 字符串以便与 MySQL INSERT INTO 命令一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26573794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com