Reputation: 32071
I'm trying to insert a JSON entry into my table, but the catch is that this JSON string has a single quote character. The below code works perfectly when the string for mainIdea is Its nice
but what I want is It's nice
with an apostrophe. What would I have to change about the below code to make it work with an apostrophe? I've tried It\'s nice
but that doesn't work either.
$jsonDic='{"mainName": "Steve Jobs","mainIdea": "Its nice"}';
$dictionaryToBeAdded=json_decode($jsonDic);
var_dump($dictionaryToBeAdded);
$data=mysql_query("SELECT arrayOfRequests FROM users WHERE email='$email'");
if($result = mysql_fetch_array( $data )) {
//get json encoded arrayOfNotifs
$decodeArray=$result['arrayOfRequests']; //this is empty
//decode it
$arrayOfRequests=json_decode($decodeArray);
//add dictionary to be added
$arrayOfRequests[]=$dictionaryToBeAdded;
$sendBackArray=json_encode($arrayOfRequests);
//update db
mysql_query("UPDATE users SET arrayOfRequests ='$sendBackArray' WHERE email='$email'");
}
Upvotes: 1
Views: 252
Reputation: 272236
You need to escape your data before you attempt to use it in a database query:
mysql_query("UPDATE users SET arrayOfRequests ='$sendBackArray' WHERE email='$email'");
// ---------------------------------------------^ ^
// --------------------------------------------------------------------------+
Imagine what would happen if $sendBackArray
contains ', email ='
and $email
contains ' OR '' = '
.
mysql_query("UPDATE users SET arrayOfRequests ='" . mysql_real_escape_string($sendBackArray) . "' WHERE email='" . mysql_real_escape_string($email) . "'");
Upvotes: 1
Reputation: 43619
You have to escape your slash as well:
$jsonDic='{"mainName": "Steve Jobs","mainIdea": "It\\\'s nice"}';
Upvotes: 0