简体   繁体   中英

PHP: else condition is not working in php

I have designed a admin login page. The if condition is working but else condition is not. After putting wrong username or password it shows blank on the same page.

if(isset($_POST['submit']))
{
    $userid = $_POST['userid'];
    $pass= $_POST['pass'];

    $sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());

    //$count=mysql_fetch_array($sql);

    $count = mysqli_num_rows($sql) or die(mysql_error());

    if($count == 1)
    {
        $_SESSION['userid'] = $userid;//$_POST['userid'];
        echo "hiii";
        //header("Location:add_menu.php");
    }
    else
    {
        echo "Wrong Username or Password";
    }
}

You used mysql_error(); which is causing the error of blank page.

Use the below code will fix your problem.

$sql = mysqli_query($DBCONNECT,$query);
$count = mysqli_num_rows($sql);

Remove or die(mysqli_error($link)) from your code that will work fine for you.

Note: mysqli_num_rows can be used for Procedural style only not for object oriented style.

Can you try with this code? Difference is putting if($count) instead of if($count==1)

if(isset($_POST['submit']))
{
    $userid = $_POST['userid'];
    $pass= $_POST['pass'];

    $sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());

    //$count=mysql_fetch_array($sql);

    $count = mysqli_num_rows($sql) or die(mysql_error());

    if($count)
    {
        $_SESSION['userid'] = $userid;//$_POST['userid'];
        echo "hiii";
        //header("Location:add_menu.php");
    }
    else
    {
        echo "Wrong Username or Password";
    }
}

Mysqli Also make result as object so you can do this :

$sql = mysqli_query($con, "SELECT * FROM users WHERE userid='$userid' and pass='$pass'") or die(mysqli_error());

your mysqli_error only will show if statement wrong and i don't think you will put wrong statement but good in development.

then you can check if statement works by if and put this :

echo $sql->num_rows;

can put in variable :

$count = mysqli_num_rows($sql) to $count = $sql->num_rows

or

if($sql->num_rows == 0) {
 // here your blank result for error
} else {
 // show result here.
}

Link : Check PHP Site Mysqli Num Rows Result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM