user5954642
user5954642

Reputation:

update column in mysql database when user logs in

I'm using this code to login user and I want to update the value in column loggedin to yes in mysql database. I tried to update it before sending header but it doesn't get updated. Where should I put the code to update the column?

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>";
        }
    }

Upvotes: 0

Views: 343

Answers (2)

Barmar
Barmar

Reputation: 782498

You're not updating the correct userid. You're updating userid = 1 instead of the ID belonging to the user who logged in. It should be:

$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE id = {$_SESSION['id']};");

Upvotes: 1

Tom
Tom

Reputation: 596

You need to change this:

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

To this:

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

Please don't use the md5() function hashing passwords, it isn't safe, use these functions instead:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php

You also use this:

if (mysqli_num_rows($query) == 1)

To check if the username exists, I suggest changing it to this:

if (mysqli_num_rows($query))

It does the same but you need less code to do it.

Other than that, please also learn how to prepare your queries before inserting them, your current code is vulnerable to SQL injection, more about that can be found here:
How can I prevent SQL injection in PHP?

Upvotes: 0

Related Questions