不确定我错过了什么?

时间:2017-07-13 15:30:22

标签: php mysql undefined

有人可以帮忙,我不确定我在这里缺少什么。

这是我得到的错误:

Notice: Undefined index: post_id in C:\xampp\htdocs\projects\charlesprater\post.php on line 6

这是我的代码,如下所示

<?php include "includes/header.php";?>

<?php
 $db = new Database();

  $id = $_GET['post_id']; 


  $query = "SELECT * FROM posts WHERE post_id = $id";

  $posts = $db->select($query) -> fetch_assoc();

  $query = "SELECT * FROM catagory";

  $catagory = $db->select($query);
  ?>



      <div class="blog-post">
        <h2 class="blog-post-title"><?php echo $posts['title'];?></h2>
        <p class="blog-post-meta"><?php echo formatDate($posts['date']);?> <a href="#"><?php echo $posts['author'];?></a></p>

        <p>
          <?php echo $posts['body'];?>
        </p>

      </div><!-- /.blog-post -->
     

2 个答案:

答案 0 :(得分:1)

您尚未说明post_id的来源:

您的变量陈述错误:

$id = $_GET['post_id']; 

将其更改为以下内容:

if (isset($_GET['post_id']))
{
    $id = $_GET['post_id'];
}
else
{
    $id = "";
}

原因是该变量可能未在URL参数中声明,并且会对页面造成致命错误。

通过添加if语句,您确保它实际上存在;如果不是id设置为NULL

答案 1 :(得分:1)

试试这段代码:

<?php
    include "includes/header.php";
    $db       = new Database();

    //Use a ternary statement to check if $_GET['post_id'] is SET before using it. 
    //If it's not set, make the variable blank.
    $id       = isset($_GET['post_id']) ? $_GET['post_id'] : "";
    if(empty($id)) {
        //kill the page if ID was not set, the script should NOT continue with no ID.
        die("There was no ID set!");
    }

    $query    = "SELECT * FROM posts WHERE post_id = $id";
    $posts    = $db->select($query)->fetch_assoc();
    $query    = "SELECT * FROM catagory";
    $catagory = $db->select($query);
?>

<div class="blog-post">
    <h2 class="blog-post-title"><?php echo $posts['title'];?></h2>
    <p class="blog-post-meta"><?php echo formatDate($posts['date']);?> <a href="#"><?php echo $posts['author'];?></a></p>
    <p>
        <?php echo $posts['body'];?>
    </p>
</div>