PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I am just start using mysql_real_escape_string, I try to use it in this login code.
But I received error, although I already follow example in the manual.
What does "%s" used for, doesn't explain on manual?
[text]Parse error: syntax error, unexpected T_STRING in ...\esc.php on line 11[/text]
The %s is used with sprintf to denote that the items following the query should be substituted into the rest of the string once the function call has completed.
$sql = sprintf("SELECT * FROM user WHERE username='" . mysql_real_escape_string($username) . "' AND password='" . mysql_real_escape_string($password) . "'");
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string(md5($_POST['password']));
$result = mysql_query("SELECT * FROM user WHERE username='$username' AND password='$password'");
$result = mysql_query("SELECT * FROM user WHERE username='$username' AND password='$password'");
while ($row = mysql_fetch_array($result))
{
//loop through your results
//print the entire array of results or
print_r($row) . "<br/>";
//print a specific row value
echo $row['table_row_name_here'];
}
This is wrong! You are now taking the md5 hash of the escaped password, not the original. Besides the fact that mysql_real_escape_string might differ from one server to another (depending on the exact SQL server which it relates to), you should always use escaping as the last step. Otherwise, subsequent steps might add new characters that require escaping.
However, when using md5 (which, by the way, is ideally replaced with sha512 + usage of a salt string) you are only getting hexadecimal output, hence there's no need to escape anything at all. It's perfectly safe to do:
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$result = mysql_query("SELECT * FROM user WHERE username='$username' AND password='$password'");
nitediver wrote:It's for user input, I have to sanitize it.
-Login
-Search
Assuming you need the user input string in an SQL query for either purpose (to search/verify a user account, or to search for content, respectively), then again: mysql_real_escape_string is all you need. It escapes the characters that requires escaping, and leaves other characters alone (which is what you want, because why would you ever want to escape other characters than necessary).
(Or were you perhaps mistakenly thinking of stripping rather than escaping?)
Or you can always try to do it yourself by entering something like ' OR 1=1; into a search form that you expect to only return a limited number of results.