0

I'm trying to put strings containing single and double quotes in my database but when I use mysqli_escape_string() on it before, it adds backslashes. If I am not mistaken, normally once in the database there should no longer be backslashes ?

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) die('Database error : '.$conn->connect_error);

$strValue = mysqli_escape_string($conn,"a'b");

$sql = "INSERT INTO test (strValue) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $strValue);
$stmt->execute();

// a'b becomes a\'b in database
Dharman
  • 30,962
  • 25
  • 85
  • 135
Elyas
  • 55
  • 1
  • 7
  • 2
    You shouldn't be using escape string though – Rotimi Apr 19 '20 at 20:50
  • But in this case there is a risk of injection ? the string comes from a user input – Elyas Apr 19 '20 at 20:53
  • 2
    no there is as far as we know no chance for a sql injection with prepared statements – nbk Apr 19 '20 at 20:58
  • 1
    Okeeey so if I understood correctly, we use mysqli_escape_string() when we don't use prepared statements to be able to "secure" the value ? And this is not necessary when using prepared statements ? – Elyas Apr 19 '20 at 21:11
  • 1
    That is correct @Miscell and that is the reason why the slashes are included when saved. Go with the prepared statements method instead. PDO also offers a prepared statement. – Funk Forty Niner Apr 19 '20 at 21:26
  • You should never ever use `mysqli_escape_string()`. Just stick to using placeholders and parameter binding. – Dharman Apr 19 '20 at 23:42
  • Okay thank you everyone ! I could have stayed trying to fix the problem for a long time .. – Elyas Apr 20 '20 at 20:57

0 Answers0