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";

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

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,

Member Avatar for iamthwee

You can effectively do the same as "break" with just loops and a few conditions.

while (!$validUser) {
  ...
}

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.

if($valid_user=1)
 echo "You are logged in";

if($valid_user==1) :P

Member Avatar for iamthwee

if($valid_user==1) :P

This is a repeat of post #2

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.