0

Is there any problem wid ths code?

$name=$_POST['txtusername'];
$password=$_POST['txtpw'];
$result = mysql_query("SELECT username,pw FROM login");
while($row = mysql_fetch_array($result))
  {
 if($name=$row['username'] && $password=$row['pw'])
 $valid_user = 1;
 else
 $valid_user = 0;
  }
  
 if($valid_user=1)
 echo "You are logged in";
 else
 echo "Enter again";
6
Contributors
7
Replies
8
Views
10 Years
Discussion Span
Last Post by iamthwee
0

Hello.

There is no syntax error in this code, but
if you want to check a value of variable you
must use operator "==", not "=".

- Mitko Kostov

0

Thankx for ur reply,bt can u plz let me know any function in PHP which can terminates the execution at any time like a "break" function in c++.As I want to terminate the loop as soon as it finds the correct match and $valid_user got value 1.

Regards,

0

What is "wrong" with your code is that you do not take benefit of MySQL capabilities to check whether user exists and passwords match.
Instead, you code in PHP a loop to scan the whole 'login' table. As you pointed out yourself, you need a way to stop scanning as soon as you have found a row. But if the expected row if deep into 'login', or does not exist, you will still fetch a lot of rows for nothing.
Using a more elaborate SQL query, your code could be:

$name=$_POST['txtusername'];
$password=$_POST['txtpw'];
$result = mysql_query("SELECT username,pw FROM login WHERE username='$name' AND pw='$password'");
$nb_rows = mysql_num_rows($result);
switch ($nb_rows){
case 0: $valid_user = 0; break;
case 1: $valid_user = 1; break;
default: /* should never occur -> error management*/
} 
if($valid_user=1)
 echo "You are logged in";
else
 echo "Enter again";

However, there is a lot more to do, for instance checking $_POST variables for special characters or code injection. You will find plenty of information about that on the web.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.