If else not working

Request help, I am using PHP 8 and am facing an issue with the if else statement.
1.) If $uname==$username is correct, the echo Confirmed is showing.
2.) If $uname is not equal to $username then the display is blank, and the else statement is not working and the echo Not Confirmed does not display.
code is as follows:

$sql = "SELECT * FROM staff WHERE staff_name='$uname' ";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$staffname=$row['staff_name'];
$password= $row['password'];
	if ($uname===$staffname) {
		echo "Confirmed";
	}
	else {
		echo " Not Confirmed";
	}
}

The code inside the while(){…} loop (which is a conditional statement) is only executed if the query matched any data.

If this query is expected to match at most one row of data, DON’T use a loop to fetch the single row. Just directly fetch the row of data and test at the same time if the row was fetched.

Next, don’t put external, unknown, dynamic values directly into an sql query statement. Use a prepared query instead. If it seems like using a prepared query with the mysqli extension is overly complicated, it is. This would be a good time to switch to the much simpler and more modern PDO extension.

Don’t copy variables to other variables for nothing. This is a waste of typing time. Just use the original variables that data is in.

    // Prepare your connection using PDO
    $pdo = new PDO('mysql:host=hostname;dbname=database', 'username', 'password');
    
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare your SQL statement
    $stmt = $pdo->prepare("SELECT password FROM staff WHERE staff_name=:staff_name");
    
    // Bind parameters to your SQL statement
    $stmt->bindParam(':staff_name', $staff_name);
    
    // Execute the SQL statement
    $stmt->execute();

    // Fetch the result into an associative array
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    // If a row was returned
    if ($row) {
        $hashed_password = $row['password'];

        // Check if the password matches
        if (password_verify($password, $hashed_password)) {
            echo "Confirmed";
        } else {
            echo "Not Confirmed";
        }
    } else {
        echo "Not Confirmed"; // No user found with the provided username
    }

This is just one way of doing it, but it gives you a basically an idea on how to do it. I would also visit https://phpdelusions.net/pdo as that is a very good source in my opinion on PDO. (I still go to it when I have a brain fart :rofl: )

Your logic is pointless and redundant. You are selecting from the db where staff_name=’$uname’ which means if the SQL gets a result, $uname will in fact be the same as $staffname or there will be no result to loop over. Your loop only loops WHILE there is a result to loop over.

Sponsor our Newsletter | Privacy Policy | Terms of Service