我想回显 php 中具有相同用户标识的所有类名

I want to echo all classNames that have the same userid in php

代码在这里:

$mysqli = new mysqli($servername, $username, $password, $database);
$userId1 = $_SESSION['user']['userId'];
$searchQuery = "SELECT ClassName FROM classrooms WHERE userid = '{$userId1}'";
echo "abc";
if ($mysqli->query($searchQuery) === TRUE) {
    echo "epic";
    while($row = $searchQuery->fetch_object()) {
        echo $row['ClassName'];
    }
} 

我正在尝试回显教室 table 中的 userId 等于会话 userId 的所有实例。帮助。

这是我们用来跟踪我正在使用 mysqli 的用户教室的 table。

ClassName  userid
yoink      25
lol        25
haha       6
yoinks     25
yeet       25
yeet1      25

事实证明,我的 post 主要是代码。因此,让我提供一些背景细节。我正在尝试制作一个 table,它将根据用户 ID 显示教室名称。因此,用户 25 将拥有教室 yoink、lol、yoinks、yeet 和 yeet1。但是 if 语句(我们的查询)实际上并没有做任何事情。

非常感谢

$searchQuery是一个字符串!!!而不是本应从 $mysqli->query() 返回的结果句柄,但您没有捕获它。

所以把代码改成

$mysqli = new mysqli($servername, $username, $password, $database);
$userId1 = $_SESSION['user']['userId'];
$searchQuery = "SELECT ClassName FROM classrooms WHERE userid = '$userId1'";
echo "abc";
if ($result = $mysqli->query($searchQuery) === TRUE) {
    echo "epic";
    while($row = $result->fetch_object()) {
        //echo $row['ClassName'];
        // you fetch an OBJECT so address it as an object
        echo $row->ClassName;
    }
} 

但是 - 重要警告

Your script is open to SQL Injection Attack. Even if you are escaping inputs, its not safe! You should consider using prepared parameterized statements in either the MYSQLI_ or PDO API's instead of concatenated values

$mysqli = new mysqli($servername, $username, $password, $database);
$userId1 = $_SESSION['user']['userId'];

$sql = "SELECT ClassName FROM classrooms WHERE userid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $userId1);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_object()) {
    echo $row->ClassName;
}