我正在尝试将我的网站切换到MySQLi,我正在按照W3schools MySQLi指南进行操作。不过,我遇到了障碍。我有一个功能来检查指定的用户是否是网站上的管理员。我已将echo
放在各个位置以查找问题所在,并且我已经发现它很可能看不到用户。 $username
设置为变量$user
。这是整个代码块(connect.php的一部分:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
session_start();
if(!isset($_SESSION["user_login"])) {
$user = "";
} else {
$user = $_SESSION["user_login"];
}
//functions
function isAdmin($username) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_get_is_admin = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$get_is_admin = mysqli_query($conn, $sql_get_is_admin);
if(mysqli_num_rows($get_is_admin) > 0) {
echo "num_rows";
while ($row = mysqli_fetch_assoc($get_is_admin)) {
$is_admin_bool = $row['admin'];
echo "while";
if($is_admin_bool == 0){
return false;
} elseif ($is_admin_bool == 1) {
return true;
}
}
} else {
echo "not found.";
}
}
?>
以下是我用来测试$user
变量的代码:
<?php
include("connect.php");
?>
<div class="main">
<h1>Welcome back, <?php echo $user; ?></h1>
foo
<?php
/*if(isAdmin($user) == true) {
echo "<div style='display: table-cell;' class='rightcell'>
<h3 style='color: #000;'>Admin Tools</h3>
<a href='userlist.php' target='_blank'>Userlist</a>
</div>";
} else {
} */
echo isAdmin($user);
?>
</div>
我还必须重新连接到数据库,否则我会在网站上收到此错误:
Notice: Undefined variable: conn in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\lark\connect.php on line 35 not found.
如果我修复它以便没有错误,它只是说“找不到。”
答案 0 :(得分:2)
$ conn变量未在您的函数中定义,例如:
function isAdmin($username) {
global $conn;
..................
}
答案 1 :(得分:1)
你的功能中没有$ conn,它被注释掉了。
function isAdmin($username) {
/*$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);*/