Home  >  Article  >  Backend Development  >  What is the solution to the problem that the content of the json_encode function in PHP contains single quotes?

What is the solution to the problem that the content of the json_encode function in PHP contains single quotes?

WBOY
WBOYOriginal
2016-12-01 01:28:002598browse

<code><?php
$arr = [
  "title" => "测试一下'单引'号保存问题",
  "name" => "tom"
];

$str = json_encode($arr);

print_r($str);

//将$str保存到数据库中,发现单引号失败; 
$sql = "UPDATE test SET str='" . $str . "' WHERE id=1";
$db->query($sql);

?>
</code>

How is it usually solved? Directly replace single quotes?

Reply content:

<code><?php
$arr = [
  "title" => "测试一下'单引'号保存问题",
  "name" => "tom"
];

$str = json_encode($arr);

print_r($str);

//将$str保存到数据库中,发现单引号失败; 
$sql = "UPDATE test SET str='" . $str . "' WHERE id=1";
$db->query($sql);

?>
</code>

How is it usually solved? Directly replace single quotes?

mysqli_real_escape_string()
PDO::quote
mysql_real_escape_string

Try not to use string splicing, use PDO and MYSQLi with Prepared Statement mechanism instead

Escape and save

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn