Page 1 of 1

Read string escaped with mysql_real_escape_string

Posted: Thu Jul 13, 2006 2:54 pm
by dgrenier
Hi there. I'm building up a site using both PHP and Mysql.

Whenever I input text in the database, I use mysql_real_escape_string() in the folowing way:

Code: Select all

$var = "It won't work";

$query = "INSERT INTO table_name VALUES ( ' " . mysql_real_escape_string( $var ) . " ' )";
If I look in the database using phpMyAdmin, I see that the string is being transformed to "It won\\\'t work". Is this normal ? I was expecting it to be more like "It won\'t work", no ?

Also, if I then extract the string from the DB to output it in an web page, it is going to be displayed like "It won\\\'t work". Is there something I should do when I extract the string which would unescape the " ' " ??

Thanks !

Posted: Thu Jul 13, 2006 3:04 pm
by Weirdan
please tell us the output of:

Code: Select all

var_dump(get_magic_quotes_gpc(), get_magic_quotes_runtime());

Posted: Thu Jul 13, 2006 3:41 pm
by dgrenier
It output:

Code: Select all

int(1) int(0)

Posted: Thu Jul 13, 2006 4:39 pm
by Oren
This $var in your real code... What dose it contain? I assume some gpc (Get Post Cookie) data, am I right?

Posted: Thu Jul 13, 2006 5:35 pm
by dgrenier
Oren wrote:This $var in your real code... What dose it contain? I assume some gpc (Get Post Cookie) data, am I right?
Well, yes and no. But the text I've got trouble with yes. So for the sake of simplicity, I'll say yes.

The query is built in a class called service_class which as different properties and a method named "create".

So it goes like this in the acutal script :

Code: Select all

$new_service = new service_class();

if( isset($_POST['service_title']) ) { $new_service->title = $_POST['service_title']; } else { $new_service->title = ''; }

if( $new_service->create() )
{
	// Notice the user that everything went well.
}
else
{
	// Notice the user that something went wrong.
}
And the code for the class :

Code: Select all

class service_class()
{

	// PROPERTIES
	var $title;

	// METHODS

	function create()
	{
		// Create a new instance of the DB class "sql_db"
		$db = new sql_db;
	
		$query = "INSERT INTO " . SERVICE_TABLE . " VALUES (' " . mysql_real_escape_string($this->title) . " ' )";
	
		if( !( $db->sql_query($query) ) )
		{
			return FALSE;
		}
		else
		{			
			// Confirms that everything went well
			return TRUE;
		}
	}
}
PS : I know I don't sanitize much my input, however, currently the script is only used internally. I'll changed that once we go live.

Posted: Thu Jul 13, 2006 6:13 pm
by Weirdan
These days magic_quotes_gpc setting considered evil. While you might not be able to turn it off (for a variety of reasons, including shared host headaches, legacy scripts requiring it to be on etc), you can (and perhaps should) undo the harm it did to user input. Here's nice example for ya: http://us2.php.net/manual/en/function.g ... .php#49612