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

WBOY
Release: 2023-03-02 14:40:02
Original
2633 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
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template