php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42569 json_encode does not escape single quotes
Submitted: 2007-09-05 18:22 UTC Modified: 2007-09-06 11:00 UTC
From: prikid at gmail dot com Assigned:
Status: Not a bug Package: JSON related
PHP Version: 5.2.4 OS: FreeBSD 6
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: prikid at gmail dot com
New email:
PHP Version: OS:

 

 [2007-09-05 18:22 UTC] prikid at gmail dot com
Description:
------------
When using json_encode() and trying to insert into mysql table field with single quotes - single quote is not escaped and mysql produces error.

Reproduce code:
---------------
$name = "Mike O'Brien";
$email = "test@tes.com";
$settings = array("name"=> $name,"email" => $email);
$json = json_encode($settings);
$sql = "INSERT INTO `users` VALUES('".$json."')";
$result = mysql_query($sql) or die (mysql_error());

Expected result:
----------------
Successfull mysql insertion with escaped single quote.

Actual result:
--------------
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 'Brien

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-09-05 18:41 UTC] bas at tobin dot nl
that's correct... JSON is just a way to serialize data to a string.

It's not the purpose of JSON to serialize data to be directly included in a statement for a specific database. 

The way MySQL escape strings is not a "universal" method as for instance MS SQL does it another way. 

If you wish to use JSON to store data in MySQL you should escape the JSON string with the specific MySQL function to escape strings, see the 
mysql_escape_string() and mysql_real_escape_string() functions
 [2007-09-05 19:06 UTC] prikid at gmail dot com
$name = "Mike O'Brien";
$name = mysql_escape_string($name);
$email = "test@test.com";
$settings = array("name" => $name,"email" => $email);
$json = json_encode($settings);

var_dump($json);

---
output is:
string(49) "{"name":"Mike O\\'Brien","email":"test@test.com"}"

Double quoted and still generates error when trying to insert into mysql db.
 [2007-09-06 11:00 UTC] jani@php.net
First you json_encode() then you do the mysql_escape_string()

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Nov 24 04:01:32 2024 UTC