Error: trying to get ownership of any object in php

0

Hello I'm getting an error very often in php the error is:

Notice: Trying to get property of non-object in C:\xampp\htdocs\login.php on line 20

The php is the following:

<?php
require 'inc/base.php';

if (!isset($_SESSION['user_id'])) {
  header("Location: index.php"); exit;
}

include 'inc/header.php';
?>
        <section>
            <h1 class="title"> now</h1>
                <?php
        $query = $db->prepare("SELECT timestamp FROM users WHERE id=?");
        $query->execute([$_SESSION['user_id']]);
        $data = $query->fetch();

                if ($data->timestamp == 0) {
                    echo "<div class=message_erreur></div>";
                } elseif (time() - $data->timestamp > 1296000) {
            // 15 jours
                    echo "<div class=message_erreur>Your right to use . Please buy again.</div>";
                } else {

                }
          ?>
                  <div class="message_erreur"></div>
          <form action="upload.php" method="post" enctype="multipart/form-data">
            Select file to upload:
            <input type="hidden" name="MAX_FILE_SIZE" value="100485760" />
            <input name="filexls" type="file">
            <input type="submit" value="Upload" name="submit">
          </form>
          <?php
                }
                ?>
        </section>
<?php
include 'inc/footer.php';

My user would have the following values:

My table:

    
asked by Mohamed El Alami 18.01.2018 в 17:15
source

1 answer

0

Since you are getting a single column in:

SELECT timestamp FROM users WHERE id=?

then the best for this case , would be to use the fetchColumn() method, which:

  

Returns a single column from the next row of a set of   results

     

PHP Manual

            <?php
    $query = $db->prepare("SELECT timestamp FROM users WHERE id=?");
    $query->execute([$_SESSION['user_id']]);
    $data = $query->fetchColumn(); //$data tendrá el valor de la columna del SELECT

            if ($data === 0) {
                echo "<div class=message_erreur></div>";
            } elseif (time() - $data > 1296000) {
        // 15 jours
                echo "<div class=message_erreur>Your right to use . Please buy again.</div>";
            } else {

            }
      ?>
  

VERY IMPORTANT NOTE: You will see that I put this line if ($data === 0) { with three signs of === . That is for you to be true only   if data is equal to 0 and is of the same type (integer). Why that?   Because if fetchColumn fails it will return FALSE and the comparison if (FALSE==0) { ... would be fulfilled, giving you then a false positive.

    
answered by 18.01.2018 в 18:10