MySQLi 查询未正确返回结果

MySQLi Query not Returning Results properly

我正在尝试将我的网站切换到 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.

如果我修复它没有错误,它只会显示 "not found."

你的函数中没有$conn,它被注释掉了。

function isAdmin($username) {
    /*$servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "lark";
    $conn = mysqli_connect($servername, $username, $password, $dbname);*/

$conn 变量未在您的函数中定义,例如:

function isAdmin($username) {
global $conn;
..................

}