gpt4 book ai didi

php - 如何在 MySQL 数据库中存储 JSON 字符串

转载 作者:IT老高 更新时间:2023-10-29 00:14:09 27 4
gpt4 key购买 nike

我使用下面的代码将 JSON 数据存储在 MySQL 表中。如果 JSON 很短但会因较长的文本而中断,则它可以正常工作。 “field_json”是一个 LONGTEXT。

$sql = sprintf("UPDATE mytable 
SET field_json = '$json_string'
WHERE id = $userid");
$result = mysql_query($sql);

我得到的错误是:

Invalid query: 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 'G '","username":"C0WB0Y","lastName":"","id":31874363},{"pathToPhoto":"22960/phot' at line 2

最佳答案

使用占位符,否则容易受到 SQL 注入(inject)攻击:http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

否则,这里有一个快速修复:http://php.net/manual/en/function.mysql-real-escape-string.php

$sql = sprintf(
"UPDATE mytable SET field_json = '%s' WHERE id = '%s'",
mysql_real_escape_string($json_string),
mysql_real_escape_string($userid)
);
$result = mysql_query($sql);

编辑

请使用 PDO ( http://www.php.net/manual/en/book.pdo.php )。 mysql 扩展已从 5.5 开始弃用

关于php - 如何在 MySQL 数据库中存储 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8990762/

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