Repeat Result for num rows in php [duplicate]

2019-08-18 05:51发布

问题:

Possible Duplicate:
i can’t make num rows inside while looping

i try allot of to make num rows in while looping to get number of rows for another tables

$select_sub_cat = mysql_query("SELECT * FROM sub_cat WHERE ct_id='".$row_main['id']."' LIMIT 8 ");
while($row_sub = mysql_fetch_array($select_sub_cat))
{
  $select_num_sub = mysql_query("SELECT * FROM market WHERE sub_cat='".$row_sub['id']."'  ");
  while($row_num_sub = mysql_fetch_array($select_num_sub))
  {
    $n = mysql_num_rows($select_num_sub);
    $smarty->assign('n',$n);
  }

 $sub_cats[] = $row_sub;
}
$smarty->assign('sub_cats',$sub_cats);

回答1:

It has no sense to put this lines:

$n = mysql_num_rows($select_num_sub);
$smarty->assign('n',$n);

Inside an inner loop. If you want to display the number of rows of a query via smarty, just make:

$select_num_sub = mysql_query("SELECT * FROM market WHERE sub_cat='".$row_sub['id']."' 
$n = mysql_num_rows($select_num_sub);
$smarty->assign('n',$n);

Inside the outer loop and you'll be fine.



回答2:

mysql_num_rows function is used to count rows in table so it will used before the while-loop.

$select_sub_cat = mysql_query("SELECT * FROM sub_cat WHERE ct_id='".$row_main['id']."' LIMIT 8 ");
while($row_sub = mysql_fetch_array($select_sub_cat))
{
  $select_num_sub = mysql_query("SELECT * FROM market WHERE sub_cat='".$row_sub['id']."'  ");
  $n = mysql_num_rows($select_num_sub);
  while($row_num_sub = mysql_fetch_array($select_num_sub))
  {

    $smarty->assign('n',$n);
  }

 $sub_cats[] = $row_sub;
}
$smarty->assign('sub_cats',$sub_cats);