简体   繁体   中英

fetching user id from login SQL table

I have recently switched my code from mysql to mysqli OOP for better practice. I am trying to fetch the user_id from my mysql table and save it in $_SESSION['user_id'] . I have tried many different iterations of my code and worked on it for hours but no luck. As of now $_SESSION['user_id'] returns nothing. It works with my old mysql code so I know its not an issue with my table. I am still new at mysqli and I would greatly appreciate any help in this matter.

Here is the PHP:

<?php

session_start();
$con = new mysqli("localhost","root","pw","db"); 

if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if(isset($_POST['submit'])){
  $query = "SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1";
  $username = $_POST['user_name'];
  $password = $_POST['pwd'];

  $stmt = $con->prepare($query);
  $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($row = $stmt->fetch()){ //fetching the contents of the row
      $_SESSION['user_id'] = $row[1];
      $_SESSION['LOGIN_STATUS']=true;
      $_SESSION['user_name'] = $username;            
      echo 'true';
    }
  }
  else {
    echo 'false';
  }
  $stmt->free_result();
  $stmt->close();
}
else{
}
$con->close();

?>

The validation works and the user name is successfully stored in the session. I think the error is in the $row = $stmt->fetch() but I cannot figure it out. Thanks in advance!

I think the issue is this line:

$_SESSION['user_id'] = $row[1];

I believe it should either be $row[0] or $row['user_id'].

(note: I used 'user_id', but it would be the name of the column that holds the IDs)

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