簡體   English   中英

如何正確地轉義JSON字符串以與MySQL INSERT INTO命令一起使用?

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

不敢相信沒有像這樣的問題……一定很簡單,但是我花了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格式包含逗號,並且這些逗號也分隔了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'...

那么有什么方法可以做到這一點,還是我必須對查詢使用某種替代語法?

嘗試這個:

$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