0

I really can't understand why this statement is wrong

$uname=$_POST['username'];
$pass=$_POST['pass'];
$str="select * from account where username='".$uname."' and password='".$pass."'";
echo $str;
echo "\n";
$str=mysql_real_escape_string($str);
$result=mysql_query($str) or die("Error: ". mysql_error(). " with query ". $str);
$num=mysql_num_rows($result);

It shows me:

select * from account where username='negin'and password='parsa' Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'negin\'and password=\'parsa\'' at line 1 with query select * from account where username=\'negin\'and password=\'parsa\'
2
  • mysql_* functions are so last year....PDO PDO PDO Commented Feb 22, 2012 at 16:25
  • ext/mysql is officially deprecated. Please use mysqli or PDO, and please also use prepared statements and placeholders. Commented Feb 22, 2012 at 16:29

4 Answers 4

3

Use mysql_real_escape_string() on the parameters, no on the whole query. You are escaping the single quotes so the query goes wrong.

Sign up to request clarification or add additional context in comments.

Comments

2

Use in this way

$uname=mysql_real_escape_string($_POST['username']);
$pass=mysql_real_escape_string($_POST['pass']);
$str="select * from account where username='".$uname."' and password='".$pass."'";

$result=mysql_query($str) or die("Error: ". mysql_error(). " with query ". $str);
$num=mysql_num_rows($result);

Comments

0

I have problems running it like that as well, the issue is in the mysql_real_escape_string() section

//Change
$str="select * from account where username='".$uname."' and password='".$pass."'";

//To
$str="select * from account where username='".mysql_real_escape_string($uname)."' and password='".mysql_real_escape_string($pass)."'";

Comments

0

Since you are using the mysql_real_escape_string() on the whole $str. It also escapes the single quotes which you have manually added inorder to insert the variables,. thus leading to errors.

Try this way.

$uname=$_POST['username'];
$pass=$_POST['pass'];

$uname = mysql_real_escape_string($uname);
$pass = mysql_real_escape_string($pass);

$str="select * from account where username='".$uname."' and password='".$pass."'";
echo $str;
echo "\n";
//$str=mysql_real_escape_string($str);
$result=mysql_query($str) or die("Error: ". mysql_error(). " with query ". $str);
$num=mysql_num_rows($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.