Skip to main content
Known Participant
May 23, 2012
Question

removing slashes

  • May 23, 2012
  • 2 replies
  • 1375 views

how do i remove slashes when using mysql_real_escape_string?

when i put in the text to the sql db, then return it, i get: "This isn\'t text." 

How would I return this without the "\"?

This topic has been closed for replies.

2 replies

Rob Hecker2
Legend
May 23, 2012

Bregent is correct, but an ultimately better solution is to use PDO prepared statements and NOT use mysql_real_escape_string. Prepared statements provide better protection, protection for more than just quotes, and eliminate the need to convert the text back and forth.

Known Participant
May 23, 2012

Ok.  how would I apply it to a variable?  Not familiar with this method.  can you run it through like a function, like clean($variable)?

Rob Hecker2
Legend
May 23, 2012

You should abandon the old MySQL connection method and use PDO or SQLi instead. At least start getting familiar with one or the other and stop using the old ,method for new work. So the connection string you use is different. For instance, here is what I use on my local server:

<?php

$dsn ='mysql:dbname=website_1;host=localhost;port=3306';

$user='root';

$password='';

try {

$dbh = new PDO($dsn, $user, $password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->query=("set names utf8");

$dbh->exec('SET CHARACTER SET utf8');

$dbh->exec('SET character_set_server=utf8');

}

catch (PDOException $e) {

  die('Connection failed: '.$e->getMessage());

}

Then, to insert into the table using prepared statements is like this:

$sql=$dbh->prepare("INSERT INTO pages set

main_photo=:main_photo");

$sql->bindValue("main_photo", $main_photo);

try{   

$sql->execute() or $response = "<p style='color:red'>INSERT FAILED!</p>";

}catch(PDOException $e)

{

echo $e;}

if ($response){

echo $response;

}

So the above is just to show you what the code looks like. Can't teach you how to use PDO in a forum post, but there are lots of tutorials on the web. I also got an ebook callee "Learning PHP Data Objects"

. . .or you may decide to go the SQLi route. You can also do prepared statements, and a lot else, with SQLi.

One of the things I love about PDO is the error reporting and handling. Note that line 4 of the code above defines the error mode, which for the testing environment is verbose. For your production environment you simply set the errormode to silent, so website users don't see all the info that you need when you debug.

Participating Frequently
May 23, 2012

Use stripslashes()