我发现很难检索登录用户的id(来自mysql数据库中的记录表)。我尝试了下面的功能来检索它,但是不起作用。
<?php
$password = md5($password);
$sql = "select * from users where username = '$username'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($count==1 && $row['password'] == $password){
$_SESSION['username'] = $row['username'];
header('location: loggedin.php');
}else{
$errorMsg = 'Invalid Username or Password';
}
这就是我想要实现的目标。
$user_id = userid(id,username);
function userid(id,username)
{
$sql = "select id from users where username = $_SESSION['username']"
$result = mysqli_query($conn, $sql);
}
?>
答案 0 :(得分:0)
您必须考虑以下因素:
return
;
变量$sql
)
您可以使用数据库连接替换id
参数:
function userid($dbcon, $username)
{
$stmt = $dbcon->prepare("SELECT id FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$stmt->close();
return $id;
}
然后,调用函数:
/** HOPE YOU DECLARED SOMEWHERE YOUR DATABASE CONNECTION PRIOR TO YOUR FUNCTION CALL **/
$username = $_SESSION['username']; /** JUST REPLACE THIS WITH ANY DATA YOU WANT **/
$user_id = userid($dbcon, $username);
困扰我的是,为什么将username
用户存储在会话变量中而不是id
?如果用户在登录时更改了用户名,该怎么办?