mercredi 27 décembre 2017

Add validation/if else statements to public class functions PHP

Hi im trying to build a simple blog using PHP PDO but ive got a bit stuck on validation/if else because what used to happen in the no class messy version was it would say "This article does not exist" but now it just shows the page with empty boxes so i was wondering how i add if/else staements to classes to make it work and show the message when the id is not one that matches in the database

 public function fetch_data($pid){

    try{
    global $pdo;

    $query = $pdo->prepare('SELECT * FROM post where post_id = ? order by post_date desc');
    $query->BindValue(1,$pid);
    $query->execute();

    return $query->fetch();

    }
     catch(PDOException $e) {
      echo '{"error":{"text":'. $e->getMessage() .'}}'; 
      }
     }

Thats the public function bit of code and the article.php page code is:

<?php

include_once('functions/main.php'); 
$post  = new Main;
$check = new Main;
$check_login = $check->logged_in();

if(isset($_GET['id'])){
    $pid = $_GET['id'];
    $post = $post->fetch_data($pid);

    $query = $pdo->prepare("UPDATE post SET post_views = post_views + 1 WHERE post_id = ?");
$query->execute(array($pid));
    ?>
<html>
    <head>
        <title><?php echo $post['post_title'];?></title>
          <meta name="viewport" content="width=device-width, initial-scale=1">


      <style>
.customimage{
background: url('<?php echo $post['post_image'];?>') !important;
}
</style>


    </head>


<body>

          <div class="pusher">
    <!-- Site content !-->
<div class="ui inverted vertical masthead center aligned segment purple customimage">
 <div class="ui text">
      <h1 class="ui inverted header">
        <?php echo $post['post_title'];?></h1>
              <br>
              <div class="ui black inverted label"> <i class="calendar icon"></i><?php echo $post['post_date'];?></div><div class="ui black inverted label"><i class="user icon"></i> <?php echo $post['post_author'];?></div><div class="ui black inverted label"><i class="unhide icon"></i> <?php echo $post['post_views']?></div>

  </div>
</div>

<div class="ui divider hidden"></div>

<div class="ui container">
<div class="ui segments">
  <div class="ui segment purple">
  <h1 class="ui header">
  <div class="content">
    <?php echo $post['post_title'];?>
     </div>
</h1>
  </div>
    <div class="ui segment">
    <?php echo $post['post_content'];?>
  </div>
  <div class="ui secondary segment">
    <button class="ui labeled icon button">
  <i class="left arrow icon"></i>
  Return to Posts</button>
  </div>
</div>
</div>

</div>
    </body>
</html>

    <?php
}else{
    header('Location:index.php');
}

?>

And i cant figure out how to make it so that when you go to ?id=876799 it then says that article doesn't exist but currently its just blank.

Thanks all help appreciated + this is not a duplicate i cant find any answers anywhere!

Aucun commentaire:

Enregistrer un commentaire