PHP 和 MySQL 登录查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10956308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:27:16  来源:igfitidea点击:

PHP and MySQL login query

phpmysqlsessioncookies

提问by Peter G

I am learning MySQL and PHP and am currently having trouble with this login process.

我正在学习 MySQL 和 PHP,目前在此登录过程中遇到问题。

It seems the MySQL query is not returning any rows and not redirecting me after a successful login.

似乎 MySQL 查询没有返回任何行,也没有在成功登录后重定向我。

PHP:

PHP:

$error_msg = "";
//checks the session to see if the user is logged in
if (!isset($_SESSION['userid'])) {
    if (!isset($_POST['submit'])) {
        $dbc = mysqli_connect('localhost', 'root', '', 'login')
        or die('Error Connecting to Database on the SQL Server');
        //grabs data from POST
        $user_username = $_POST['username'];
        $user_password = $_POST['password'];
        //lookup username and password in the database
        if (!empty($user_username) && !empty($password)) {
            $query = "SELECT userid, username FROM tuser WHERE username = '$user_username' AND password = SHA('$user_password')";
            $res = mysqli_query($dbc, $query);
            //login is ok so set the user ID and username cookies, redirect to homepage
            if (mysqli_num_rows($res) == 1) {
                $row = mysqli_fetch_array($res);
                $_SESSION['userid'] = $row['userid'];
                $_SESSION['username'] = $row['username'];
                setcookie('userid', $row['userid'], time() + (60 * 60 * 24 * 30), "/");
                setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30), "/");
                setcookie('email', $row['email'], time() + (60 * 60 * 24 * 30), "/");
                setcookie('password', $row['password'], time() + (60 * 60 * 24 * 30), "/");
                //redirect after successful login
                header("Location: index.php");
            } else {
                //the username and password are incorrect so set error message
                $error_msg = 'Sorry, you must enter a valid username and password to log in. <a href="Signup.php">Please sign up!</a>';
            }
        }
    }
}

HTML:

HTML:

<form action="login_process.php" method="post" class="login">
 Username: <input type="text" name="username"/>
 Password: <input type="password" name="password"/>
 <input type="submit" value="submit"/>
</form>

Sorry for the sloppy code, I am familiar with PHP and MySQL and teaching myself how to do this. I made some changes and the code submits, but it does not redirect me, it just goes to login_process.php and does nothing. What am i missing? I appreciate all the help, thank you everyone!

抱歉,代码草率,我熟悉 PHP 和 MySQL 并自学如何执行此操作。我做了一些更改并提交了代码,但它没有重定向我,它只是转到 login_process.php 并且什么也不做。我错过了什么?我感谢所有的帮助,谢谢大家!

    <?
    session_start();

    $error_msg = "";

    //checks the session to see if the user is logged in

if (!isset($_SESSION['user_id'])) 
{
    if (isset($_POST['submit'])) 
    {

        $user_username = mysql_real_escape_string($_POST['username']);
        $user_password = mysql_real_escape_string($_POST['password']);

        $dbc = mysqli_connect('localhost', 'root', '', 'login')
        or die('Error Connecting to Database on the SQL Server');
        //grabs data from POST

            //lookup username and password in the database
            if (!empty($user_username) && !empty($password)) 
            {

                $query = "SELECT userid, username FROM tuser WHERE username = '$user_username' AND password = SHA('$user_password')";

                $res = mysqli_query($dbc, $query);

                //login is ok so set the user ID and username cookies, redirect to homepage
                if (mysqli_num_rows($res) == 1) 
                {
                    $row = mysqli_fetch_array($res);

                    $_SESSION['user_id'] = $row['userid'];
                    $_SESSION['user'] = $row['username'];
                    setcookie('userid', $row['userid'], time() + (60 * 60 * 24 * 30), "/");
                    setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30), "/");
                    setcookie('email', $row['email'], time() + (60 * 60 * 24 * 30), "/");
                    setcookie('password', $row['password'], time() + (60 * 60 * 24 * 30), "/");

                    //redirect after successful login
                    header("Location: home.php");
                    echo mysqli_error($dbc);

                } 
                else 
                {
                    //the username and password are incorrect so set error message
                    $error_msg = 'Sorry, you must enter a valid username and password to log in. <a href="Signup.php">Please sign up!</a>';

                    header("Location: home.php");
                    echo mysqli_error($dbc);

                }
            }
            else
            {
                $error_msg = 'Please enter a username and password to log in. <a href="Signup.php">Please sign up!</a>';

                header("Location: home.php");
                echo mysqli_error($dbc);

            }

    }
}

    ?>

回答by Austin

I'm not sure if that's all all of your code but you must session_start()before you can access $_SESSION

我不确定这是否是您的全部代码,但您必须session_start()先访问,然后才能访问$_SESSION

Your code only queries unless a post isn't set so change it:

您的代码仅查询,除非未设置帖子,因此请更改它:

if (isset($_POST['submit'])) {

  //your code

}

Also, be sure to escape user input to prevent sql injection:

另外,一定要转义用户输入以防止 sql 注入:

$user_username = mysql_real_escape_string($_POST['username']);

Make sure it's not a error in your SQL:

确保它不是您的 SQL 中的错误:

echo mysqli_error($dbc);

回答by Dave_Peachy

You are not executing anything the because of this line:

由于这一行,您没有执行任何操作:

if (!isset($_POST['submit'])) {

It should be change to

应该改成

if (isset($_POST['submit'])) {

isset() will return TRUE if that variable is set. !isset() will return TRUE if it is notset

如果设置了该变量,isset() 将返回 TRUE。如果设置,!isset() 将返回 TRUE

回答by colonelclick

I see two problems:

我看到两个问题:

Your boolean is backwards on the line (i.e. remove the ! mark)

您的布尔值在线上向后(即删除!标记)

if (!isset($_POST['submit'])) {

The second problem is that your input button lacks a name="submit" attribute, so it is never being passed, so the variable will never be present regardless of the first problem.

第二个问题是你的输入按钮缺少 name="submit" 属性,所以它永远不会被传递,所以无论第一个问题如何,变量都不会出现。

回答by Peter G

Thank you everyone, got it working.

谢谢大家,搞定了。

<?
//Start session
session_start();

$_SESSION['message'] = "";

//Include database connection details
require_once('global.php');


//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
    die("Unable to select database");
}

if(!empty($login) && !empty($password)) {

    $login = mysql_real_escape_string($_POST['login']);
    $password = mysql_real_escape_string($_POST['password']);

    $query = "SELECT * FROM tuser WHERE username = '$login' AND password = SHA('$password')";
    $data = mysql_query($query);

    if($data) {
        if (mysql_num_rows($data) == 1 ) {
            $row = mysql_fetch_assoc($data);
            $_SESSION['userid'] = $row['userid'];
            $_SESSION['username'] = $row['username'];
            $_SESSION['message'] = "Welcome,&nbsp;" . $_SESSION['username'];
            header('Location: member.php');
            exit();
        }
        else {
            $_SESSION['message'] = "Please enter a valid username or password";
            header('Location: error.php');
            exit();
        }

    }
    else {
        die("Query failed");
    }

}
else {
    $_SESSION['message'] = "Please enter a username or password";
    header('Location: error.php');
    exit();
}


?>