[英]fetching user id from login SQL table
I have recently switched my code from mysql to mysqli OOP for better practice. 我最近将代码从mysql切换到mysqli OOP,以获得更好的实践。 I am trying to fetch the user_id
from my mysql table and save it in $_SESSION['user_id']
. 我试图从我的mysql表中获取user_id
并将其保存在$_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. 到目前为止, $_SESSION['user_id']
返回任何内容。 It works with my old mysql code so I know its not an issue with my table. 它可以与我的旧mysql代码一起使用,因此我知道它与表无关。 I am still new at mysqli and I would greatly appreciate any help in this matter. 我还是mysqli的新手,在此方面的任何帮助将不胜感激。
Here is the PHP: 这是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. 我认为错误在$row = $stmt->fetch()
但我无法弄清楚。 Thanks in advance! 提前致谢!
I think the issue is this line: 我认为问题是此行:
$_SESSION['user_id'] = $row[1]; $ _SESSION ['user_id'] = $ row [1];
I believe it should either be $row[0] or $row['user_id']. 我认为应该是$ row [0]或$ row ['user_id']。
(note: I used 'user_id', but it would be the name of the column that holds the IDs) (注意:我使用了'user_id',但这将是保存ID的列的名称)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.