0
$val = "I'm string"; 

For this type of string I am using the addslashes function, which convert string into like this:

"I\'m string" 

and store into the database. When I get all data from database in array of fields and passed array in

json_encode($arr); 

In response I get the string with a extra slash like this:

"I\\'m string" 

And I wanted to remove that extra slash which is added by json_encode. how I do that??

11
  • 2
    You shouldn't be using addslashes with databases. Use prepared statements. It looks like you're actually adding a literal slash to your string instead of escaping the apostrophe. Commented Jul 3, 2018 at 13:02
  • 1
    Use prepared parameterized statements in either the MYSQLI_ or PDO API's and this problem dissappears and you dont need strip or add slashes anywhere Commented Jul 3, 2018 at 13:04
  • 1
    If you use prepared statement correctly, you don't need addslashes Commented Jul 3, 2018 at 13:07
  • 1
    Yes, without you having to do ANYTHING special at all Commented Jul 3, 2018 at 13:09
  • 2
    This questions attracts lots of answers which are downvoted. This would not happen if you had shown your code for writing to the database Commented Jul 3, 2018 at 13:10

3 Answers 3

2

If you really want an answer to this question you can reverse your addslashes with stripslashes.

But never use addslashes function to escape values you are going to send to mysql.

Use native prepared statements, mysqli_real_escape_string() or PDO::quote.

BUT NOTE:

  1. Don't use a vulnerable character set for connection encoding (use utf8 or something)
  2. Use a higher version of MySQL than 5.7.6.

Read more about character set issues here: http://php.net/manual/en/mysqlinfo.concepts.charset.php

Sign up to request clarification or add additional context in comments.

4 Comments

Changed my answer to add to the encoding issues.
It is safe enough if you are using quotes around the variables.
@RiggsFolly The bug NO_BACKSLASH_ESCAPES was already fixed in 5.7.6. And both functions are safe. But you were right it should mention you need a higher version than 5.7.6. The character issues are documented in PHP docs.
2

You can use stripslashes.

However, you should use prepared statements. That way you don't need to worry about escaping your values.

Comments

-2

It might even be possible with this (though I thought it was forward slash / only:

json_encode($array, JSON_UNESCAPED_SLASHES); 

But heed to the comments and Script47's answer and just fix it properly.

1 Comment

Woah nice, those downvotes. Would love some feedback on my answer since you all think it's clearly wrong? Prepared statements will fix OP's problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.