简体   繁体   中英

PHP login validator + store user id

I already store the logged username in a $_SESSION[user_name] variable. How can I additionally store the user_id in the $_SESSION[user_id] variable. I've tried to use $stmt->fetch_array(MYSQLI_NUM); but have had no luck.

I have a MySQL table as such:

login:

+---------------+-------------+-------------+-------------+
|    auto_id    |  username   |  password   |   user_id   |
+---------------+-------------+-------------+-------------+
|       0       |      a      |      b      |      1      |
+---------------+-------------+-------------+-------------+
|       1       |      c      |      d      |      2      |
+---------------+-------------+-------------+-------------+
|       2       |      e      |      f      |      3      |
+---------------+-------------+-------------+-------------+

my php login validator is:

<?php
session_start();
require_once('php/config.php');

if(isset($_POST['submit'])){
  $username = $_POST['user_name'];
  $password = $_POST['pwd'];
  $user_id_col = "3";

  $stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
  $stmt->bind_param('ss', $username, $password);
  $stmt->execute();
  $stmt->bind_result($username, $password);
  $stmt->store_result();
  if($stmt->num_rows == 1)  //To check if the row exists
  {
    while($stmt->fetch())
    {
  $_SESSION['LOGIN_STATUS']=true;
  $_SESSION['user_name'] = $username;
  $_SESSION['user_id'] = $user_id;
  echo 'true';
    }
  }
  else {
    echo 'false';
  }
  $stmt->close();
}
else{
}
$con->close();
?>

The variable $user_id is never defined in your code. I assume you are using PDO for your querying, this should do the trick

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['LOGIN_STATUS']=true;
$_SESSION['user_name'] = $username;
$_SESSION['user_id'] = $row['user_id'];

Since you only expect one result, you don't need a while-loop.

If you wonder about the cryptic PDO::FETCH_ASSOC , you can read about it in the manual .

$stmt->fetch() returs a value, but you never store it in a variable.

Use

while($data = $stmt->fetch()) { 
    $_SESSION['userid'] = $data['userid'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM