You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用户登录/注册后MySQL数据异常返回字符'u'问题求助

从MySQL获取用户数据时返回字符'u'而非预期的用户信息

我在实现用户注册/登录功能后,尝试从MySQL数据库获取用户数据,但系统却返回字符'u',而数据库中并无该字符。预期输出应为(从上到下从左到右):用户名、等级、货币、钻石、红宝石,对应值分别为用户名、0、0、0、0。我已重构代码两次,问题仍未解决。

相关代码

index.php(注册/登录页面)

<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function start(){ closeForm(); closeRegForm(); }
function openForm() { document.getElementById("myForm").style.display = "block"; closeRegForm(); }
function closeForm() { document.getElementById("myForm").style.display = "none"; }
function openRegForm() { document.getElementById("myRegForm").style.display = "block"; closeForm(); }
function closeRegForm() { document.getElementById("myRegForm").style.display = "none"; }
</script>
</head>
<body onload="start()">
<nav>
<button class="button" type="submit" onclick="openForm()">Влез</button>
<button class="buttonReg" type="submit" onclick="openRegForm()">Регистрирай се</button>
<img src="Logo4.png" class="Logo" alt="Logo">
</nav>
<div class="form-popupRegister" id="myRegForm">
<form method="post" action="server.php" class="form-containerReg">
<h1>Регистрация</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">
<label for="email"><b>Е-майл</b></label>
<input type="email" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">
<label for="password_1"><b>Парола</b></label>
<input type="password" placeholder="Въведете парола" name="password_1">
<label for="password_2"><b>Повторете Парола</b></label>
<input type="password" placeholder="Въведете парола повторно" name="password_2">
<button type="submit" class="btnReg" name="reg_user">Register</button>
<button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
</form>
</div>
<div class="form-popup" id="myForm">
<form method="post" action="server.php" class="form-container">
<h1>Влизане</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" value="<?php echo $username; ?>">
<label for="password"><b>Парола</b></label>
<input type="password" name="password">
<button type="submit" class="btn" name="login_user">Login</button>
<button type="button" class="btn-cancel" onclick="closeForm()">Close</button>
</form>
</div>
</body>
</html>

index2.php(数据展示页面)

<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function getUserStats(){
<?php
$queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
$userStats = mysqli_query($db,$queryThree);
$userStatsTwo = mysqli_fetch_assoc($userStats);
?>
}
</script>
</head>
<body onload="getUserStats()">
<div class="navWrapper">
<div class="statistics">
<div class="profilePicture" name="profilePicture">
<label class="profilePictureLabel" for="profilePicture"><b><?php echo userStatsTwo['username']; ?></b></label>
</div>
<div class="money" name="money">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['money']; ?></b></label>
</div>
<div class="diamond" name="diamond">
<label class="diamondLabel" for="diamond"><b><?php echo userStatsTwo['diamonds']; ?></b></label>
</div>
<div class="ruby" name="ruby">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['ruby']; ?></b></label>
</div>
<div class="level" name="level">
<label class="levelLabel" for="level"><b>Level:<?php echo userStatsTwo['level']; ?></b></label>
</div>
</div>
</div>
</body>
</html>

server.php(数据处理页面)

<?php
session_start();
// initializing variables
$username = "";
$email = "";
$idQuery = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'censored', 'id9159890_registerdb');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) { array_push($errors, "The two passwords do not match"); }
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM `register` WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) {
// if user exists
if ($user['username'] === $username) { array_push($errors, "Username already exists"); }
if ($user['email'] === $email) { array_push($errors, "email already exists"); }
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level) VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
mysqli_query($db, $query);
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}
}
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($password)) { array_push($errors, "Password is required"); }
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM `register` WHERE username='$username'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>

问题分析

出现这个问题主要有几个核心错误:

  1. 用户ID存储错误:

    • 在server.php的注册逻辑中,你把SQL查询语句$idQuery = "SELECT ID FROM ..."直接存入了$_SESSION['userid'],而不是执行查询后获取的实际用户ID值。
    • 登录逻辑中甚至没有获取和存储用户ID,导致index2.php中无法拿到正确的用户标识。
  2. PHP与JS混合逻辑错误:

    • 在index2.php中,你把PHP查询代码放在了JS函数getUserStats()里,这是完全错误的——PHP是服务器端语言,页面加载时就会执行所有PHP代码,和JS函数的执行时机无关,导致查询逻辑根本没有按预期触发。
  3. 变量引用错误:

    • 输出用户数据时遗漏了变量前的$符号(比如echo userStatsTwo['username']),PHP会把userStatsTwo当作未定义的常量,最终输出的是字符串字面量的一部分(这就是你看到字符'u'的原因)。
  4. 未从Session获取用户ID:

    • index2.php中的$idQuery没有从Session中读取登录/注册时存储的用户ID,导致查询条件为空或错误,无法获取正确的用户数据。

修复方案

1. 修正server.php的用户ID存储逻辑

注册部分修改:

// 注册成功后,正确获取用户ID并存入Session
$query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level) VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
mysqli_query($db, $query);

// 执行查询获取用户ID
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
$result_id = mysqli_query($db, $idQuery);
$user_id = mysqli_fetch_assoc($result_id);

// 存入实际的ID值,而非SQL语句
$_SESSION['username'] = $username;
$_SESSION['userid'] = $user_id['ID'];
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');

登录部分修改:

if (mysqli_num_rows($results) == 1) {
    // 获取用户数据,提取ID并存入Session
    $user = mysqli_fetch_assoc($results);
    $_SESSION['username'] = $username;
    $_SESSION['userid'] = $user['ID'];
    $_SESSION['success'] = "You are now logged in";
    header('location: index2.php');
}

2. 重构index2.php的逻辑

移除错误的JS函数包裹,直接在服务器端完成查询,并修正变量引用:

<?php 
include('server.php');

// 检查用户是否已登录,未登录则跳回登录页
if(!isset($_SESSION['userid'])){
    header('location: index.php');
    exit;
}

// 从Session获取用户ID
$idQuery = $_SESSION['userid'];

// 执行查询获取用户数据
$queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
$userStats = mysqli_query($db, $queryThree);

// 检查查询是否成功
if(!$userStats){
    die("数据库查询失败: " . mysqli_error($db));
}

$userStatsTwo = mysqli_fetch_assoc($userStats);

// 检查用户是否存在
if(!$userStatsTwo){
    die("未找到该用户");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="navWrapper">
<div class="statistics">
<div class="profilePicture" name="profilePicture">
<label class="profilePictureLabel" for="profilePicture"><b><?php echo $userStatsTwo['username']; ?></b></label>
</div>
<div class="level" name="level">
<label class="levelLabel" for="level"><b>Level:<?php echo $userStatsTwo['level']; ?></b></label>
</div>
<div class="money" name="money">
<label class="rubyLabel" for="ruby"><b><?php echo $userStatsTwo['money']; ?></b></label>
</div>
<div class="diamond" name="diamond">
<label class="diamondLabel" for="diamond"><b><?php echo $userStatsTwo['diamonds']; ?></b></label>
</div>
<div class="ruby" name="ruby">
<label class="rubyLabel" for="ruby"><b><?php echo $userStatsTwo['ruby']; ?></b></label>
</div>
</div>
</div>
</body>
</html>

3. 额外建议

  • 避免使用md5加密密码,推荐使用password_hash()和password_verify(),安全性更高。
  • 为了防止SQL注入,建议使用预处理语句(prepared statements)代替直接拼接SQL字符串。
  • 在Session中存储用户信息后,记得在用户退出时销毁Session。

内容的提问来源于stack exchange,提问作者Xander Nedelchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:29:12