2013-04-07 132 views
-2

我試圖找回那些活躍在類別1應該有46個員額的所有帖子,但它輸出4和職位是從12類沒有類別1.mysql的不返回正確的結果

$cat_id = 1; 
$limit = 12; 
// Count posts 
$count_posts = count_cat_posts($cat_id); 

這是count_posts功能

// Count category posts 
    function count_cat_posts($cat_id){ 

     $stmt = $dbh->prepare("SELECT * FROM mjbox_posts WHERE post_active = 1 AND cat_id = ?"); 
     $stmt->bindParam(1,$cat_id); 
     $stmt->execute(); 

     $rows = $stmt->fetchAll(); 
     $count_posts = count($rows); 
     return $count_posts; 
    } 

我所有的職位存儲在數組中

// Retrieve all active posts in this category and order by lastest first 
    $resultarray = retrieve_cat_posts($cat_id, $offset, $limit); 

這是我正在使用的功能。

// Retrieve active posts 
    function retrieve_cat_posts($cat_id, $offset, $limit){ 


     // Get all the posts 
     $stmt = $dbh->prepare(" SELECT p.post_id, post_year, post_desc, post_title, post_date, img_file_name, p.cat_id 
           FROM mjbox_posts p 
           JOIN mjbox_images i 
           ON  i.post_id = p.post_id 
             AND i.cat_id = p.cat_id 
             AND i.img_is_thumb = 1 
             AND post_active = 1 
             AND p.cat_id = ? 
           ORDER BY post_date 
           DESC 
           LIMIT ?,?"); 
     $stmt->bindParam(1, $cat_id, PDO::PARAM_INT); 
     $stmt->bindParam(2, $offset, PDO::PARAM_INT); 
     $stmt->bindParam(3, $limit, PDO::PARAM_INT);       
     $stmt->execute(); 


     while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 

       $resultarray[] = $row; 
     } 

     return $resultarray; 
    } 

我沒有添加偏移量變量,但它是正確的。

我輸出的帖子是這樣的:

foreach($resultarray AS $value){ 
        $filename = substr($value['img_file_name'],9); 
        $cat_id = $value['cat_id']; 
         // Wraps image, title, category 
         echo '<div class="itemWrap">'; 
         // Item Image 
         echo '<a href="post.php?post_id='.$value['post_id'].'" class="itemImageLink"><img class="itemImage" src="create_thumb.func.php?path=img/fs/'.$filename.'&save=0&width=160&height=120" alt="'. stripslashes(stripslashes($value['post_title'])) .'"></a>'; 
         // Item Title 
         echo '<div class="itemTitle"><a href="post.php?post_id='.$value['post_id'].'" class="itemTitleLink">' .stripslashes(stripslashes($value['post_title'])). '</a></div>'; 
         // Item Category 
         echo '<div class="itemCat"><a href="cat.php?cat_id='.$cat_id.'">'. $cat_name = get_cat_name($cat_id) .'</a></div>'; 
         // close itemWrap 
         echo '</div>'; 
       } 

當我在MySQL查詢窗口中運行它的查詢工作。 那麼,爲什麼從$cat_id = 1獲得類別12的帖子呢?

+0

您沒有使用您在其他問題中給出的解決方案。爲什麼要問?儘管如此,這個問題又是一個過於侷限的問題。不幸的是,問答網站不適合在您的代碼中發現拼寫錯誤。 – 2013-04-07 13:41:47

+0

您是否在'retrieve_cat_posts()'函數中看到任何錯誤。我認爲我把它縮小到了那裏。 – crm 2013-04-07 13:52:27

回答

-1

在SELECT查詢中使用JOIN而不是LEFT JOIN需要至少有一個圖像存在int mjbox_images,它符合規定的條件。

而且這條線

echo '<div class="itemCat"><a href="cat.php?cat_id='.$cat_id.'">'. $cat_name = get_cat_name($cat_id) .'</a></div>'; 

有些離奇,設定回波語句內變量的值。

+0

查詢本身沒有任何問題,但謝謝 – crm 2013-04-07 13:53:46