<?php
$con = mysql_connect('localhost','root','');

<?php
    $con = mysql_connect('localhost','root','');
    $db = mysql_select_db('myuploads',$con);$un = $_GET['usname'];
    $ps = $_GET['passwd'];
    $retr = mysql_query("SELECT uname,password FROM user WHERE uname = '$un' ");
    while($row = mysql_fetch_assoc($retr)) {
        if($row['uname'] == $un) {
            if($row['uname']== $un && $row['password'] == $ps) {
                echo "Welcome ".strtolower($un);
            }
            else
                echo "Password doesnt match";
        }
        else
            echo "User ".$un." doesnt exist";
    }
?>

Dani AI

Generated

As already explained, the reason the "User ... doesnt exist" branch in the original code never runs is a logic/location problem: that else is inside the while(...) body. When the SELECT returns zero rows the while condition is false and the loop body never executes, so any inside-the-loop else is unreachable. Fix the control flow by checking for "no rows" first, then handling the single-row case (password check) afterwards.

Move to parameterized queries and hashed passwords instead of the old mysql_* calls. The ext/mysql API was removed in PHP 7, so modern code should use mysqli or PDO. Use prepared statements to avoid SQL injection and use password_hash()/password_verify() for safe password storage and checking. Example using PDO + password_verify:

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=myuploads;charset=utf8mb4','dbuser','dbpass', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
} catch (PDOException $e) {
    error_log($e->getMessage());
    exit('Database error');
}

$username = trim($_POST['usname'] ?? '');
$password = $_POST['passwd'] ?? '';

$stmt = $pdo->prepare('SELECT password FROM user WHERE uname = ? LIMIT 1'); // 'password' should store the hash
$stmt->execute([$username]);
$hash = $stmt->fetchColumn();

if ($hash === false) {
    echo "User " . htmlspecialchars($username, ENT_QUOTES, 'UTF-8') . " not found";
} elseif (password_verify($password, $hash)) {
    echo "Welcome " . htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
} else {
    echo "Password doesn't match";
}

Moving off ext/mysql is required for current PHP versions. (php.net) Prepared statements (PDO/mysqli) are the recommended way to avoid SQL injection. (php.net) Use password_hash()/password_verify() for safe password handling. (php.net)

Quick tips and checks:

  • If keeping legacy code temporarily, test whether the query returned rows before entering a loop; handle the "0 rows" case separately (that’s the root of your symptom).
  • Enforce a UNIQUE index on uname so you get at most one row for a username.
  • Use POST (not GET) for credentials; never put passwords in URLs or logs.
  • In development enable proper error reporting/logging; in production log errors and show generic messages.
  • Always escape output (e.g., htmlspecialchars) when echoing user values to avoid XSS.

Recommended Answers

All 6 Replies

it does not get into the final else statement, nothing gets displayed, when i enter a username that is not present in the database, not even a warning or error

Hello 'viveksraman'.

You have to debug this by echoing before and after the conditional statements, and by adding the "or die(mysql_error());" after a function (check later in my code).

Or try to put this $row = mysql_fetch_assoc($retr); just before the while.

Anyway you can add this to your code
$row_num = mysql_num_rows($retr);
this will return the number of rows found in the database, if it's 0 than nothing found, if you want the username to be unique then the variable should be equal to one and NOT greater than one!!

Here's how I write your idea:

$connection = mysql_pconnect("localhost","root","password") or die(mysql_error());
$database = "amirbwb";

$un = $_GET['usname'];
$ps = $_GET['passwd'];

mysql_select_db($database , $connection) or die(mysql_error());
$query = mysql_query("SELECT uname,password FROM user WHERE uname = '$un' AND password = '$ps'");
$row = mysql_fetch_assoc($query);
$num_rows = mysql_num_rows($query);

//I considered the user is unique, if not change '== 1' to '> 0'
if($num_rows == 1){
    echo "Hello " . $row['uname'];
}else
{
    echo $un." not found";
}

PS: THE CODE IS WRITTEN DIRECTLY HERE AND NOT TESTED

I just noticed that you want the option, Password doesn't match. OK
Just replace this in my previous code:
I recommend you to try both codes cuz you may use the first code block in your future ;)

mysql_select_db($database , $connection) or die(mysql_error());
$query = mysql_query("SELECT uname,password FROM user WHERE uname = '$un'");
$row = mysql_fetch_assoc($query);
$num_rows = mysql_num_rows($query);

//I considered the user is unique, if not change '== 1' to '> 0'
if($num_rows == 1){
    if($ps != $row['password']){
        echo "Password doesn't match";
    }else
    {
        echo "Welcome " . $row['uname'];
    }
}else
{
    echo $un." not found";
}

Good Luck
PS: THE CODE IS WRITTEN DIRECTLY HERE AND NOT TESTED

thanks for the reply bro, but i hav a question, what is the problem with my last else statement, it does no execute, when i enter a username tha is not been listed in my database. look at the seventh line of my code, if that coondition is not satisfying then the control must have jumped over to fourteenth line, but i get nothing, when my if condition gets wrong, y so ?

Hi amir bro,i don't get any type of bug or anything. if i enter a username that is ther in my db it works prettygood, even while checking whether the username and password belongs to the same row, it works fine, but i dont get anything when i enter a username that is not listed in my db, with my coding, i expect to print "User doesnt exist", i will be glad if i get the root cause for this, am a newbie to PHP :)

Hello again 'viveksraman', the problem is that you are doing a while loop in which the first condition is false, in other words
while($row = mysql_fetch_assoc($retr))
is the same as
while(false) which will not read the content and will directly jump to the last close curly brkt

while($row = mysql_fetch_assoc($retr))
is only used if you are sure you have more than 1 row as a result of you query "SELECt ..."

since here there is no result, mysql_num_rows($retr) = 0;
$row = mysql_fetch_assoc($retr) is $row = false
therefor while(false) and the body is not executed

I want to repeat one thing, in checking username and password, in most cases we don't use while, cuz username are unique, but it's not a problem if you use it :)
to fix your code

SOLUTION OF YOU CODE:
1 - Back to your code, remove the else that is not executing and will never.
2 (First Method) - And you can add a boolean variable like found = false; before the while loop.
Inside the while loop write found = true;
and after exiting the while loop, write this condition

if(!found)
    echo $un . " not found";

2 (Second Method) - you can simply add this after the exiting the while loop:

if(mysql_num_rows($retr) == 0)
    echo $un . " not found";

Hope I was clear in my explanation :)
Good Luck

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.