用户登录时更新mysql数据库中的列

时间:2016-04-13 19:08:45

标签: php mysql

我正在使用此代码登录用户,我想在mysql数据库中将登录列中的值更新为yes。我尝试在发送标头之前更新它,但它没有得到更新。我应该在哪里放置代码来更新列?

if (isset($_POST['login']))
    {
    $username = trim(mysqli_real_escape_string($con, $_POST['username']));
    $password = trim(mysqli_real_escape_string($con, $_POST['password']));
    $md5password = md5($password);

    // check user and password match to the database

    $query = mysqli_query($con, "SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");

    // check how much rows return

    if (mysqli_num_rows($query) == 1)
        {

        // login the user
        // get the id of the user

        $fetch = mysqli_fetch_assoc($query);

        // start the session and store user id in the session

        session_start();
        $_SESSION['id'] = $fetch['id'];
        $_SESSION['username'] = $fetch['username'];
        $query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE userid = 1;");
        header("Location: message.php");
        }
      else
        {

        // show error message

        echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
        }
    }

1 个答案:

答案 0 :(得分:0)

你需要改变这个:

UPDATE user SET loggedin = 'yes' WHERE userid = 1;

对此:

mysqli_query($con, 'UPDATE user SET loggedin = 'yes' WHERE userid = 1');

请不要使用md5()函数哈希密码,不安全,请改用以下功能:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php

你也使用这个:

if (mysqli_num_rows($query) == 1)

要检查用户名是否存在,我建议将其更改为:

if (mysqli_num_rows($query))

它也是如此,但你需要的代码更少。

除此之外,请在插入之前了解如何prepare您的查询,您当前的代码容易受到SQL注入攻击,有关详细信息,请参阅此处:
How can I prevent SQL injection in PHP?