2016-02-29 43 views
0

我是一個初學者的PHP。PHP&MYSQL-未定義的變量:the_post_id和警告:mysqli_fetch_assoc()期望參數1是mysqli_result,布爾值

說明:未定義變量:the_post_id在C:\ XAMPP \ htdocs中\仁達\ post.php中第27行

警告:mysqli_fetch_assoc()預計參數1被mysqli_result,布爾在C中給出:\ XAMPP \ htdocs中\仁達\ post.php中上線30

這是線27

 $query ="SELECT * FROM posts WHERE post_id = {$the_post_id}"; 

這是線30

    while ($row = mysqli_fetch_assoc($select_all_posts_query)) { 

這是我的PHP代碼

   <?php 

       if(isset($_GET['p_id'])) { 

        $the_post_id = $_GET['p_id']; 

       } 


       $query ="SELECT * FROM posts WHERE post_id = {$the_post_id}"; 
       $select_all_posts_query = mysqli_query($connection, $query); 

       while ($row = mysqli_fetch_assoc($select_all_posts_query)) { 
        $post_id = $row['post_id']; 
        $post_title = $row['post_title']; 
        $post_author = $row['post_author']; 
        $post_date = $row['post_date']; 
        $post_image = $row['post_image']; 
        $post_content = $row['post_content']; 

        ?> 
+0

1日檢查您是否獲得在'$ _GET'第二連接字符串缺少任何參數。 – Apb

+0

請閱讀[我可以問哪些主題](http://stackoverflow.com/help/on-topic) 和[如何提出一個好問題](http://stackoverflow.com/help/how-to -ask) 和[完美的問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) – RiggsFolly

回答

0

第一個「通知」的錯誤可以通過不執行所有的代碼,如果的p_id不存在被阻止。第二個錯誤是因爲mysqli_query可能返回false(請參閱the PHP documentation for the function)。

我可能會做這樣的事情:

<?php 

    if (isset($_GET['p_id'])) { 

     $the_post_id = $_GET['p_id']; 

     $query = "SELECT * FROM posts WHERE post_id = $the_post_id"; 
     $select_all_posts_query = mysqli_query($connection, $query); 

     if ($select_all_posts_query) { 
      while ($row = mysqli_fetch_assoc($select_all_posts_query)) { 
       $post_id = $row['post_id']; 
       $post_title = $row['post_title']; 
       $post_author = $row['post_author']; 
       $post_date = $row['post_date']; 
       $post_image = $row['post_image']; 
       $post_content = $row['post_content']; 
      } 
     } 
     else { 
      // handle error condition (the query failed) 
     } 
    } 
    else { 
     // handle p_id not being in $_GET 
    } 

?> 
相關問題