简体   繁体   中英

Having trouble with php login page

I am newbie to php and I was just building simple login page with php here is my code:

<?php 
    $username=$_POST['uname'];
    $password=$_POST['pass'];
    $con=mysqli_connect("localhost","root","","myblog");
    $sql="SELECT username,password FROM users WHERE username='$username' AND password='$password'";
    if(mysqli_query($con,$sql)) {
        echo "login successful";
    } else {
        echo "login failed";
    }
?>

The problem is I am getting "login successful" msg even with the wrong credentials(random imputs). Please someone guide me.

try this

you have to check whether result produced or not ... Instead of query correct or not..

<?php 
$username=$_POST['uname'];
$password=$_POST['pass'];
$con=mysqli_connect("localhost","root","","myblog");
$sql="SELECT username,password FROM users WHERE username='$username' AND password='$password'";

$result =mysqli_query($con,$sql);
$count = mysqli_num_rows($result);

if($count>0)
{
echo "login successful";
}
else
{
echo "login failed";
}
?>

Try to do it like this. use mysqli_num_rows()

  $result = mysqli_query($con,$sql);

   if(mysqli_num_rows($result) >0){
       echo "login successful";
    }else {
       echo "login failed";
    }

you dont have to check if query was succesfull, but if result has some rows..

$answer = mysqli_query($con,$sql)
if(  mysqli_num_rows($answer)>0   ) {  ... there is such record...   }

try this

<?php 
    $username=$_POST['uname'];
    $password=$_POST['pass'];

    $username = mysql_real_escape_string(stripslashes($username));
    $password = mysql_real_escape_string(stripslashes($password));

    $con=mysqli_connect("localhost","root","","myblog");
    $sql="SELECT username,password FROM users WHERE username='$username' AND password='$password' LIMIT 1 ";
    $result = mysqli_query($con,$sql);
    if($row = mysqli_fetch_assoc($result)) 
    {
        echo "login successful";
    }   
    else 
    {
        echo "login failed";
    }
?>

Your Condition is not proper, also use LIMIT 1 whenever you trying to fetch exact one result.

You should pass your post variable through mysql_real_escape_string and stripslashes to prevent from sql injections

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