在PHP中使用电子邮件和密码登录时出现问题

时间:2019-02-26 15:45:21

标签: php database authentication login

<?php
$msg = "";
session_start();

if (isset($_POST['submit'])) 
{
    $con = new mysqli('localhost', 'root', '', 'sconnect');
    $email = $con->real_escape_string($_POST['email']);
    $semail=$email;
    $password = $con->real_escape_string($_POST['password']);
    $sql = $con->query("SELECT * FROM users WHERE email='$email' AND 
    password='$password';");

    if ($email == "" || $password == "")
        $msg = "Please check your inputs!";
    else if ($sql) 
    {
        $_SESSION['user'] = $semail;
        header('Location:../home.php');
    }
    else 
    {
        $msg = "Please check your inputs!";
    }
}
?>

使用此代码,我可以使用密码字段中的任何输入登录。请解决问题。

1 个答案:

答案 0 :(得分:-2)

您要检查的变量是$ sql,如果您在其中存储任何值,它将为true。在您的情况下,您可以使用SQL查询。因此它将始终返回true。您应该在if语句中检查从SELECT查询返回的num行。

$msg = "";
session_start();
if (isset($_POST['submit'])) {
    $con = new mysqli('localhost', 'root', '', 'test');
    $email = $con->real_escape_string($_POST['email']);
    $semail = $email;
    $password = $con->real_escape_string($_POST['password']);
    $sql = $con->query("SELECT * FROM users WHERE email='$email' AND password='$password';");

    if ($email == "" || $password == "")
        $msg = "Please check your inputs!";
    else if ($sql->num_rows) {
        $_SESSION['user'] = $semail;
        header('Location:../home.php');
    } else {
        $msg = "Please check your inputs!";
    }
}