我如何将代码仅回声一次,而不是两次



满足要求后两次我的代码回声HeyHello

这应该检查一个人是否已上载,具体取决于他们是否显示任何消息。

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $sqlImg = "SELECT * FROM users WHERE idUsers='$current'";
        $resultImg = mysqli_query($conn, $sqlImg);
        while ($rowImg = mysqli_fetch_assoc($resultImg)) {
            if ($rowImg['profile_img'] == 0) {
                echo "hey";
            } else {
                echo "Hello";
            }
        }
    }
}

我希望输出一次回声一次,但是实际输出将两次回荡。

您不需要两个循环。无论是否与$current匹配,外循环都为表中的每个用户运行。对于他们每个人,您都在进行另一个刚刚获得$current用户并回应其状态的查询。

如果idUsers是唯一的密钥,则您甚至不需要任何循环。只需进行一个查询并获取行。

您还应使用准备好的语句来防止SQL注入。

$stmt = $conn->prepare("SELECT profile_img FROM users WHERE idUsers = ?");
$stmt->bind_param("s", $current);
$stmt->execute();
$result = $stmt->get_result();
$rowImg = $result->fetch_assoc();
if ($rowImg['profile_img'] == 0) {
    echo "hey";
} else {
    echo "Hello";
}

最新更新