Home > Backend Development > PHP Tutorial > 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?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-02 14:40:02
Original
2670 people have browsed it

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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

Related labels:
php
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template