Jump to content

Mysqli_Real_Escape_String - Problem


mds1256

Recommended Posts

Hi

 

When post'ing from a form on a signin page I am allowing the user to type in their username and password.

 

If the details cannot be found in the database then I send an error message to the form but populate the input box for username with the value that was submitted.

 

Now the problem is that I run this value through mysqli_real_escape_string when it is posted so if the sql query finds no rows then it displays the signin form again but with the value of $username (which has been mysqli_real_escape_string escaped).

 

So when the value is displayed it puts a slash into the username before the character that needs escaping (as I have put in a single quote to test).

 

What would be the best way to echo out the value of $username without the slash, also do I need to use htmlspecialchars when echoing the $username value back into the input field?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/272318-mysqli_real_escape_string-problem/
Share on other sites

You should do this by wrapping mysql_real_escape_string () around the variable when you add the value to the SQL string, and not overwriting the original value. By using sprintf () this can be done in a more readable manner than just adding the function calls in the string itself.

$query = "INSERT INTO table (field_1, field_2, field_3) VALUES ('%s', %d, '%s')";
$query = sprintf ($query, mysql_real_escape_string ($string_1), $number, mysql_real_escape_string ($string_2));

 

Though, preferably you should move over to MySQLI or PDO, and use prepared statements. (You can read more about them in the PHP manual.)

You should do this by wrapping mysql_real_escape_string () around the variable when you add the value to the SQL string, and not overwriting the original value. By using sprintf () this can be done in a more readable manner than just adding the function calls in the string itself.

$query = "INSERT INTO table (field_1, field_2, field_3) VALUES ('%s', %d, '%s')";
$query = sprintf ($query, mysql_real_escape_string ($string_1), $number, mysql_real_escape_string ($string_2));

 

Though, preferably you should move over to MySQLI or PDO, and use prepared statements. (You can read more about them in the PHP manual.)

 

I see, will look into prepared statements :) Thank you!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.