Jump to content

session is not updating the lastlogin value


dig_dug

Recommended Posts

Hi

The following  php code is to update values and pass it to the database .

The problem is it's not updating the $lastlogin value and I can't see anything wrong with it, can anybody tell me what I'm doing wrong.

Any help would be appreciated.

public function login($postArray)
    {
        $jsonArr = array("status" => "unknown");
        
        $username = $postArray['username'];
        $pass = sha1($postArray['password']);
        $ip = $_SERVER['REMOTE_ADDR'];
        $date = gmdate("Y-m-d H:i:s"); //login time  
        
        
        $rowsNum = self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");
        
        //successfully logged in
        if($rowsNum == 1)
        {
            //update the record
            self::$dbConnection->exec_query("UPDATE `users` SET `cur_ip`='$ip', `last_login`='$date' WHERE `username`='$username', `password`='$pass'");
            
            //pull the information from the database
            $f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");
            $userid = $f['id'];

            $lastlogin = $f['last_login'];
            
            //set the login session
            $dataArray = array("userid" => $userid, "username" => $username, "lastlogin" => $lastlogin);
            
            //set status
            $jsonArr['status'] = "login_success";
            $jsonArr['userdata'] = $dataArray;
        }
        else
        {
            //set status
            $jsonArr['status'] = "login_fail";
        }
        
        return $jsonArr;
    }


Link to comment
Share on other sites

Here's a hint....   When you log a user in you SELECT the user id and store it in your session.  If you don't have an id (user id) column in your user table, add one. It should be a primary key and auto incrementing.

 

SELECT user.id FROM tblUser user WHERE username = 'THE_USER_NAME' and password = 'PASSWORD_HASH';

 

If that returns a row with the user.id in it,  then you have a successful login... then you plop that user.id value in the session  $_SESSION['authUserID'] = (int)$row['id'];

 

 

Then when you do other queries you can do them by the user id  .

 

UPDATE `users` SET `cur_ip`='$ip', `last_login`='$date' WHERE users.id = $_SESSION['authUserID'];

Link to comment
Share on other sites

Here's a hint....   When you log a user in you SELECT the user id and store it in your session.  If you don't have an id (user id) column in your user table, add one. It should be a primary key and auto incrementing.

 

SELECT user.id FROM tblUser user WHERE username = 'THE_USER_NAME' and password = 'PASSWORD_HASH';

 

If that returns a row with the user.id in it,  then you have a successful login... then you plop that user.id value in the session  $_SESSION['authUserID'] = (int)$row['id'];

 

 

Then when you do other queries you can do them by the user id  .

 

UPDATE `users` SET `cur_ip`='$ip', `last_login`='$date' WHERE users.id = $_SESSION['authUserID'];

Hi

Thanks for the fast answer.

That's what I'm doing, I'm gonna attach the whole code so you can see what Iam doing exactly.

<?php
require_once 'config.php';

class Extras {
    
    public static function generatePassword($length)
    {
      // start with a blank password
      $password = "";
      // define possible characters
      $possible = "0123456789abcdfghjklmnopqrstvwxyz-_ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
      // set up a counter
      $i = 0; 
      // add random characters to $password until $length is reached
      while ($i < $length) { 
        // pick a random character from the possible ones
        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

        // we don't want this character if it's already in the password
        if (!strstr($password, $char)) { 
          $password .= $char;
          $i++;
        }
      }
      // done!
      return $password;
    }
 
}



class Validate {
    static public $dbConnection;
     
    //checks string length
    function str_len($str, $len)
    { 
        if(strlen($str) < 6)
        {
            return array(false, "String is shorter than 6 characters!");
        }

        if(strlen($str) > $len)
        {
             return array(false, "String is longer than {$len} characters!");
        }

        return array(true, "correct_length");
    }
    
    
    //username validate using regex
    function username_validate($str, $pattern)
    {
        if (!preg_match($pattern, $str))
        {
            return array(false, "Invalid username, please use alphanumeric characters only!");
        }
        
        return array(true, "correct_username");
    }


    //database validate
    function username_exists($str, $condition)
    {
        $str = self::$dbConnection->escape($str);
        
        if(self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `username`='$str'") > $condition)
        {
            return array(false, "Username exists in our database!");
        }
        
        return array(true, "doesnt_exist_in_db");
    }


    //email validate
    function email_validate($email, $pattern)
    {   
        if (!preg_match($pattern, $email))
        {
            return array(false, "Please enter a valid email!");
        }
        
        return array(true, "correct_email");
    }
    
    
    //database validate
    function email_exists($str, $condition)
    { 
        $str = self::$dbConnection->escape($str);
        
        if(self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `email`='$str'") > $condition)
        {
            return array(false, "Email exists in our database!");
        }
        
        return array(true, "doesnt_exist_in_db");
    }

    function is_number($str, $cond)
    {
        if(is_numeric($str) != $cond)
        {
            return array(false, "User ID must be a numeric number!");
        }
        
        return array(true, "correct_format");
    }



    //validate all data through all functions
    function validateData($postArray, $keyNames)
    {
        $statusArr = array();
        $jsonArr = array("status" => "unknown");
         
        //keynames array 
        foreach ($keyNames as $keyName => $checks)
        {
            //check if keynames are set
            if(!array_key_exists($keyName, $postArray))
            {
                //not in the response 
                $statusArr[$keyName][] = $keyName." variable is not set!";
            }
            else
            {
                $value = $postArray[$keyName];
                //now do further validations
                //validation functions
                foreach ($checks as $funcName => $condition)
                {
                    $dataReturned = $this->$funcName($value, $condition);
                    $valid = $dataReturned[0];
                    $error = $dataReturned[1];

                    //if check is not valid return error msg
                    if(!$valid)
                    {
                       $statusArr[$keyName][] = $error;
                    } 

                }


            }

        }
        
        if(empty($statusArr))
        { 
            $jsonArr["status"] = "ok"; 
        }
        else
        {
            $jsonArr["status"] = "error";
            $jsonArr["errors"] = $statusArr;
        }
         
        return $jsonArr; 
    }
   
    function registerAccount($postArray)
    {
        $jsonArr = array("status" => "unknown");
        
        $username = $postArray['username'];
        $email = $postArray['email'];
        $pass = sha1($postArray['password']);
        $ip = $_SERVER['REMOTE_ADDR'];
        $date = gmdate("Y-m-d H:i:s"); //reg time
        $hash = Extras::generatePassword("30");

        //now try to register our account
        $status = self::$dbConnection->exec_query(
                "INSERT INTO `users` (`username`, `email`, `password`, `veri_hash`, `reg_date`, `reg_ip`, `cur_ip`, `last_login`, `banned`)".
                " VALUES ('$username', '$email', '$pass', '$hash', '$date', '$ip', '$ip', '$date', '0')");
        
        //return success statement
        if(!$status)
        {
            $jsonArr['status'] = "register_fail";
        }
        else
        {
            $jsonArr['status'] = "register_success";
        }
        
        return $jsonArr;
    }
    
    
    public function login($postArray)
    {
        $jsonArr = array("status" => "unknown");
        
        $username = $postArray['username'];
        $pass = sha1($postArray['password']);
        $ip = $_SERVER['REMOTE_ADDR'];
        $date = gmdate("Y-m-d H:i:s"); //login time  
        
        
        $rowsNum = self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");
        
        //successfully logged in
        if($rowsNum == 1)
        {
            //update the record
            self::$dbConnection->exec_query("UPDATE `users` SET `cur_ip`='$ip', `last_login`='$date' WHERE `username`='$username', AND `password`='$pass'");
            
            //pull the information from the database
            $f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");
            $userid = $f['id'];

            $lastlogin = $f['last_login'];
            
            //set the login session
            $dataArray = array("userid" => $userid, "username" => $username, "lastlogin" => $lastlogin);
            
            //set status
            $jsonArr['status'] = "login_success";
            $jsonArr['userdata'] = $dataArray;
        }
        else 
        {
            //set status
            $jsonArr['status'] = "login_fail";
        }
        
        return $jsonArr;
    }

}

//set db connection
Validate::$dbConnection = $db;

?>

Link to comment
Share on other sites

Doing...

 

$rowsNum = self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");

 

to check rows before doing...

 

$f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");

 

is silly. you're doing the same thing twice making your hardware work that much harder. you're using resources where you don't have to.

 

you can do this...

 

$f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'"); # get user info for user user log in attempt.

 

if ( ($cnt=count ($f)) === 0) echo 'username or password is wrong';

elseif ( $ cnt === 1 ) echo 'hi, we are now signing you in more efficiently! bonus!';

else throw new exception ('serious design flaw in your database');

Link to comment
Share on other sites

Doing...

$rowsNum = self::$dbConnection->rows_num("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");
to check row count before doing...

$f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'");
is silly. you're doing the same thing twice making your hardware work that much harder. you're using resources where you don't have to.

 

you can do this...

$f = self::$dbConnection->query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'"); # get user info for user user log in attempt.

if ( ($cnt=count ($f)) === 0) echo 'username or password is wrong'; 
elseif ( $ cnt === 1 ) echo 'hi, we are now signing you in more efficiently! bonus!';
else throw new exception ('serious design flaw in your database');
Edited by objnoob
Link to comment
Share on other sites

I also want you to understand that your rows_num method is pointless.

1. you can count the rows of data your query returns.

2. in the event you only ever needed the row count, and not any of the data a little further in the code. use query method too. SELECT count(*) FROM tblPageHits; again, if you only need the count of rows in the database,,, ask the database to give you the just the count. if you need the data but also need or want to check the count, ask the database for the data and count it yourself.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.