我有以下内容来抓取父类别下的所有类别:
<?php
$childrows = array();
$result2 = mysql_query("SELECT * FROM categories WHERE category_parent_id='$cid'"); while
($row = mysql_fetch_array($result2)){
$childrows [] = $row['category_id'];
print_r($childrows); }
?>
返回:
Array ( [0] => 47 ) Array ( [0] => 47 [1] => 48 ) Array ( [0] => 47 [1] => 48 [2] => 63 ) Array ( [0] => 47 [1] => 48 [2] => 63 [3] => 64 ) Array ( [0] => 47 [1] => 48 [2] => 63 [3] => 64 [4] => 68 ) Array ( [0] => 47 [1] => 48 [2] => 63 [3] => 64 [4] => 68 [5] => 69 )
我遇到的问题是下一阶段,我需要从products表中计算存储在数组中的类别(category_id)下的产品数量(product_id)。
一定有办法!! ??
谢谢你的期待。 乙
完整代码:
<?php
if ($num_rows == 0) {
$result2 = mysql_query("SELECT * FROM categories WHERE category_parent_id='$cid'");
while ($row = mysql_fetch_array($result2)){
$childrows [] = $row['category_id'];
}
$category_string = implode(",",$childrows);
$result3 = mysql_query("SELECT category_id, COUNT(product_id)
FROM products
WHERE category_id IN ($in_string)");
$result3 = mysql_fetch_array($result3);
$result3 = $result3[1];
echo $result3;
}
else {
echo $num_rows;
}
?>
但这只是重新出现:
注意:未定义的变量:第31行的in_string(WHERE category_id IN($ in_string)“);)
警告:mysql_fetch_array():提供的参数不是第32行的有效MySQL结果资源($ result3 = mysql_fetch_array($ result3);)
答案 0 :(得分:1)
$result3 = mysql_query("SELECT category_id, COUNT(product_id)
FROM products
WHERE category_id IN ($in_string)");
$result3 = mysql_fetch_array($result3);
$result3 = $result3[1];
echo $result3;
答案 1 :(得分:0)
首先,要注意SQL注入,如果$ cid是不受信任的输入(来自用户的输入),至少应该是mysql_real_escape_string($ cid)。
您的问题对我来说并不是特别清楚,但是您只需要进行第二次查询即可获得给定数组的每个类别的产品数量,您可以这样做:
/* After obtaining $childrows */
$category_string = implode(",",$childrows);
$result3 = mysql_query("SELECT COUNT(product_id) FROM products
WHERE category_id IN ($category_string)");
$ result3将包含表示所有产品计数的单个数字记录集的句柄,每个类别计算一次,属于$ childrows数组中的类别
答案 2 :(得分:0)
SELECT COUNT(product_ID)
FROM product
WHERE category_id IN (HERE you implode your categories)