我正在开发一个网页,该网页将显示数据库中用户的信息。首先,我编写了一些代码来从数据库中获取名字并回显它。我最初测试的用户的每个字段(用户名、名字、姓氏、密码)都填写为 "1"
。为了进一步测试它,我尝试注销并尝试使用不同的帐户,即firstName “Admin”
。对于此帐户以及所有非第一个帐户,我收到此错误:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in /var/www/vhosts/s4001175-ct4009.uogs.co.uk/httpdocs/profile.php on line 19
通过查看类似的线程,我了解到这可能是因为查询返回 False 而不是数组,因为它应该返回,这让我相信销毁 session 无法正常工作,但是手动删除 cookie,关闭 chrome仍然给出相同的结果。
代码:
<?php
// Starts the session
session_start();
// If a user is not logged in, redirect to index to login
if(!isset($_SESSION['login_user'])){
header("Location:index.html");
}
include 'config.php';
$currentUser = ($_SESSION['login_user']);
$selectUserInfo= "SELECT FirstName FROM User WHERE Username = $currentUser";
$userInfoResult = $connection -> query($selectUserInfo);
$row = mysqli_fetch_array($userInfoResult);
$FirstName = $row['FirstName'];
$LastName = $row['LastName'];
?>
使用变量:
<?php echo "<h1>$FirstName $LastName</h1>"; ?>
按照建议,我实现了一个 While 循环,如下所示,并修改了 SQL 以选择我需要的所有信息,而不仅仅是名字:
<?php
// Starts the session
session_start();
// If a user is not logged in, redirect to index to login
if(!isset($_SESSION['login_user'])){
header("Location:index.html");
}
// Includes everything from config php to set up DB connection
include 'config.php';
// Creates var from current users username
$currentUser = ($_SESSION['login_user']);
// Query to locate the first name using the existing login as a locator
$selectUserInfo= "SELECT * FROM User WHERE Username = $currentUser";
//Executes the query and creates a variable from it
$userInfoResult = $connection -> query($selectUserInfo);
//$row = mysqli_fetch_array($userInfoResult);
while ($row = mysqli_fetch_array($userInfoResult)) {
$FirstName = $row['FirstName'];
$LastName = $row['LastName'];
}
?>
同样的错误仍然存在,但消失了一分钟,但仍然无法正常工作。无论出于何种原因,似乎存在一些奇怪的不一致,但我收到的错误仍然是:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in /var/www/vhosts/s4001175-ct4009.uogs.co.uk/httpdocs/profile.php on line 21
最佳答案
你可以试试这个:
<?php
session_start();
if(!isset($_SESSION['login_user'])){
header("Location:index.html");
}
include 'config.php';
// Creates var from current users username
$currentUser = ($_SESSION['login_user']);
$sql = "SELECT * FROM User WHERE Username = '$currentUser'";
$query = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($query)) {
$FirstName = $row['FirstName'];
$LastName = $row['LastName'];
}
?>
关于php - 显示名字的查询仅适用于一个用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66090543/