我正在尝试从登录的任何用户获取不同的统计信息。然后回显这些统计信息。登录时我正在使用用户名设置会话。然后我试图从这个用户名中获取id并再次检查具有相同ID的表,然后从该表中获取行。
我的猜测是,因为我在登录时只使用用户名启动会话,所以获取数据的代码不会起作用,因为会话不提供id行。我不确定如何做到这一点,或者我是否正确。
我感谢所有的帮助,我真的被困在这里。
这是我的登录代码:
$query = "SELECT password FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
//USERDATA
$dbPassword = $row['password'];
if (password_verify($password, $dbPassword))
{
// echo "The details are correct.";
$_SESSION['loggedin'] = $username;
require_once('../../frontend/templates/account-actions.php');
}
else
{
echo "Passwords do not match!";
}
这是我从登录用户名的id获取统计数据的代码:
$id = $_SESSION['loggedin'];
$query = "SELECT * FROM stats WHERE id='$id'";
$stmt = mysqli_query($conn, $query);
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);
答案 0 :(得分:1)
我已将您的代码转换为mysqli
准备语句,采用程序方法。
$username = "username_to_search";
$password = "password"; //Password is in plain text since password hash has been used.
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE username = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $username); //"s" defines the type of data in the following variables, i.e. String for $username.
/* execute query */
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$total_rows = mysqli_stmt_num_rows($stmt);
mysqli_stmt_bind_result($stmt, $id_fetched, $username_fetched, $password_fetched); //store every field fetched from the table in sequence. Note that I have added _fetched to make it easier to identify later.
if ($total_rows > 0) {
while(mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $password_fetched)) {
$_SESSION['user_id'] = $id_fetched;
$_SESSION['username'] = $username_fetched;
require_once('../../frontend/templates/account-actions.php');
}
else {
echo "Invalid Password!";
}
}
} else {
echo "Invalid Username!";
}
一旦正确存储了SESSION变量,现在您可以轻松找到与此相关的所有内容。用户$_SESSION["user_id"]
进行搜索。