我有以下数组:
Array
(
[1] => Array
(
[time] => 07:30
[event] => Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin
)
)
(原始事件字符串是:"名人管风琴独奏会 – Sophie-Véronique Cauchefer-Choplin",我用 htmlentity 和 ENT_QUOTES)
当我使用json_encode时,事件字符串以 NULL 形式返回,并在 MySQL 中保存为空字符串。
如果我不使用html实体。我将在我的数据库中得到这个:"名人管风琴独奏会u2013 Sophie-Vu00e9ronique Cauchefer-Choplin"。我使用了很多方法,但我仍然无法将此字符串转换回其原始字符串。
我真的需要一些帮助,我希望你能给我一个解决方案,用json编码一个像上面这样的UTF-8字符串,然后将其保存到MySQL,然后解码回原来的。我搜索了一段时间,但仍然找不到解决方案。
非常感谢!
在我看来
,您不关心清理sql查询中的值http://php.net/manual/en/function.mysql-real-escape-string.php
简单的例子:我们有结构表:
CREATE TABLE `test` (
`text` VARCHAR(1024) NULL DEFAULT '0'
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
和 PHP 脚本
header("Content-type:text/html;charset=utf8");
$ar = array
(
1 => Array
(
'time' => '07:30',
'event' => 'Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin'
)
);
$mysqli = new mysqli('localhost','root', '', 'test');
$mysqli -> query("INSERT INTO `test` (`text`) VALUES ('" . json_encode($ar) . "')"); // we not escape characters like ', ", '
// now we use mysqli::real_escape_string
$mysqli -> query("INSERT INTO `test` (`text`) VALUES ('" . $mysqli -> real_escape_string(json_encode($ar)) . "')"); // here we escape characters
$mysqli_result = $mysqli -> query("SELECT * FROM `test");
while($result = $mysqli_result -> fetch_assoc()){
var_dump(json_decode($result["text"],true));
}
var_dump
的结果是:
array
1 =>
array
'time' => string '07:30' (length=5)
'event' => string 'Celebrity Organ Recital u2013 Sophie-Vu00e9ronique Cauchefer-Choplin' (length=68)
array
1 =>
array
'time' => string '07:30' (length=5)
'event' => string 'Celebrity Organ Recital – Sophie-Véronique Cauchefer-Choplin' (length=63)
第二var_dump
正常