PDA

View Full Version : Reversing the effects of mysql_real_esape_char() when selecting from DB


bubbles19518
10-27-2007, 04:40 AM
So I have data that I enter into a DB, I clean it using this code:

foreach($_POST as $key => $value)
{
$_POST[$key] = mysql_real_escape_string($_POST[$key]);
}


It adds the \ to ",',/... This obviously stays there when I SELECT it from the DB. I was wondering if there was a way to bring the text back to its original state without doing str_replace() to all the different characters it changes.

Inigoesdr
10-27-2007, 06:28 PM
You can try using stripslashes() (http://php.net/stripslashes) or an array of replacements for str_replace() (http://php.net/str_replace).

kbluhm
10-28-2007, 03:58 PM
Escape characters added by mysql_real_escape_string() will not be present in the database.

// original data
$string = "This can't be right.";

// store data
$qry = sprintf( 'INSERT INTO `table` ( `field` ) VALUES ( \'%s\' )', mysql_real_escape_string($string ) );
$res = mysql_query( $qry );

// retrieve data
$qry = 'SELECT * FROM table';
$res = mysql_query( $qry );
$row = mysql_fetch_assoc( $res );
echo $row['field']; // This can't be right.


My guess is your host has magic_quotes on. If this is the case, turn them off, or use stripslashes() at the top of your script before storing the data:

if ( get_magic_quotes_gpc() )
{
foreach ( $_POST as $k => $v )
{
$_POST[$k] = is_array( $v )
? array_map( 'stripslashes', $v )
: stripslashes( $v );
}
}