使用 isset() 检查值是否存储在数据库中

Checking if value is stored in the database with isset()

如果用户不为内容付费(通过 Stripe),我想显示一个页面,因此必须在数据库中检查他是否付费。如果他付款,我将字符串“ok”存储到状态中,如果他不付款,则它只是空白。

现在我不确定为什么下面的代码不起作用:

<?php
if(!isset($_SESSION["username"])) {
?>
    <a href="login.php">Login</a> to watch Satellite data.
<?php
    $query = 'SELECT status 
                FROM users 
                WHERE username="'.$_SESSION["username"].'"';
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) { 
        $status = $row["status"]; 
        if ($status !== "ok") {
            $status_notpaid = true;
        } 
    }
} elseif(isset($_SESSION["username"]) && isset($status_notpaid))  {     
    include("notpaid.php"); 
} else {
?>

<?php 
$query = 'SELECT id 
            FROM users 
            WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
?>

Hello <strong><?php echo $_SESSION["username"];?></strong> | 

<?php 
while ($row = $result->fetch_assoc()) { 
    echo $row["id"]; }
?> 

我不确定为什么 elseif(isset($_SESSION["username"]) && isset($status_notpaid)) { include("notpaid.php") ; } 无效。

我假设登录脚本设置 $_SESSION["username"] 如果登录成功。

将用户 table 的 id 放在更有意义,因为我认为这是主键。如果愿意,您也可以将 username 保留在会话中,这样可以完全节省 运行 部分代码。

<?php

if(!isset($_SESSION["userid"])) {
    # user not logged in direct to login, and nothing else
    echo '<a href="login.php">Login</a> to watch Satellite data.';
}

if (isset($_SESSION["userid"])) {
    # then we are logged in 

    # So now we check if they paid
    $query = 'SELECT status 
                FROM users 
                WHERE id=?';
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $_SESSION["userid"])
    $stmt->execute();
    $result = $stmt->get_result();
    
    # we had better only be getting one row as a resut of that query
    # so a loop is totally unnecessary
    $row = $result->fetch_assoc();
    $status = $row["status"]; 
    if ($status !== "ok") {
        include("notpaid.php"); 
    } 
}
?>

Hello <strong><?php echo $_SESSION["username"];?></strong> | $_SESSION['userid']