gpt4 book ai didi

php - Mysql结果设置session变量

转载 作者:行者123 更新时间:2023-11-29 02:03:42 25 4
gpt4 key购买 nike

我想使用 mysql 查询的结果来设置 session 变量,但是目前我正在努力设置它。

我的代码是:

<?php

ob_start("ob_gzhandler");

?>
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');

// Start session
session_start();

// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}

// Connect to database
$mysqli = @new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}

// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);

// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);

// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true

$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;


redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>

然后我用以下方法测试 session 变量:

<?php 
session_start();
echo "Login Status is:".$_SESSION['logged_in'];
echo "<br/>";
echo "Auth status is level:".$_SESSION['auth_lvl'];
?>

在我的测试页面上,登录的 session 可以正常显示正确的信息,但是 auth lvl 变量什么都不显示。

我只能假设我没有正确调用我一开始设置变量所用的信息。

如有任何帮助,我们将不胜感激。

艾伦。

我注意到并且我一直在尝试这些建议的是,如果我设置了一个定义而不是尝试从数据库中检索一个值,那么该值将返回到我的测试页面上。即

$_SESSION['auth_lvl'] = 'test';

这告诉我是我从数据库中提取数据并尝试将其设置为 $_SESSION['auth_lvl'] 的方式导致了问题。

最佳答案

找到问题了。

代码如下:

$result = $mysqli->query($sql); 

// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {

// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );

// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['Auth_lvl'];


// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;

因为我在这段代码中使用了 mysqli,所以我没有注意到在//ADD THIS SET OF LINES 代码片段中缺少“i”。当我将代码更改为:

$data = mysqli_fetch_assoc( $result );

一切都被点燃了。

感谢您的帮助。

关于php - Mysql结果设置session变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10230581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com