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

Time:11-08

I want to display a page, if user doesn't pay for content (via Stripe) and therefore have to check in DB if he paid or not. If he paid, I store string "ok" into status and if he doesn't it's just blank.

enter image description here

Now I'm not sure why the following code doesn't work:

<?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"]; }
?> 

I'm not sure why elseif(isset($_SESSION["username"]) && isset($status_notpaid)) { include("notpaid.php"); } doesn't work.

CodePudding user response:

I am assuming the login script sets $_SESSION["username"] if login is successful.

It would make more sense to put the id of the users table, as I assume that is the primary key. You can keep username in session as well if you like and that would save you running some of this code at all.

<?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']
  • Related