用于在每个类别列表上显示prodCount的脚本

时间:2014-07-03 20:05:06

标签: php mysql count echo product

我需要您的帮助来解决我在网页上显示产品数量的问题。

我正在为我的网站重新使用书中的示例并对其进行修改以反映每个类别的计数。

显示网页中的当前结果显示两个类别反映的计数为3而不是A类= 3和B类= 1。

当前显示网页

CATEGORY
A(3)
B(3)

应该是:

CATEGORY
(3)
B (1)

以下是ff:

MYSQL表格

类别表

╔═══════════════════════════╗
║ CategoryID | CategoryName ║
╠═══════════════════════════╣
║ 1 | A                     ║
║ 2 | B                     ║
╚═══════════════════════════╝

产品表

╔══════════════════════════════════════╗
║ ProductID | CategoryID | ProductName ║
╠══════════════════════════════════════╣
║ 1 | 1| Num0ne                        ║
║ 2 | 1 | NumTwo                       ║
║ 3 | 1 | NumThree                     ║
║ 4 | 2 | NumFour                      ║
╚══════════════════════════════════════╝

// php script

<?php
function get_categories() { 
global $db; 
     $query = 'SELECT * FROM categories 
               ORDER BY categoryID'; 
try { 
  $statement = $db->prepare($query); 
  $statement->execute(); 
  $result = $statement->fetchAll(); 
  $statement->closeCursor(); 
  return $result; 
} catch (PDOException $e) { 
display_db_error($e->getMessage()); 
    }  
}

function get_product_count_per_category( ) {
global $db;
    $query = 'SELECT productID, productName,
              (SELECT COUNT(*) FROM products
              WHERE products.categoryID = categories.categoryID) 
              AS productCount 
              FROM categories
              ORDER BY categoryID';

$statement = $db->prepare($query);
$statement->bindValue(':category_id', $category_id);
$statement->execute( );
$result = $statement->fetchAll( );
$statement->closeCursor( );

$product_count = $result[0]['productCount']; 
return $product_count;

//获取类别列表并显示计数

switch (action) {
  case 'list_products' :
    $categories = get_categories( );
    $product_count = get_product_count_per_category( );
    break;
}
 ?>

<html>

  <?php foreach ($categories as $category) : ?>      
  <li>
    <a href="<?php echo $app_path . 
      'catalog?action=list_products' . 
      '&amp;category_id=' . $category['categoryID']; ?>">

    <?php echo $category['categoryName']  ." ("  .  $product_count . “ )” ;?>
    </a>
  </li>
<?php endforeach; ?>

</html>

非常感谢你。

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT count(*), CategoryID
from Product
inner join Category
on Product.CategoryID = Category.CategoryID
group by CategoryID