Home > Backend Development > PHP Tutorial > 这段循环要如何纠正

这段循环要如何纠正

WBOY
Release: 2016-06-13 12:25:46
Original
852 people have browsed it

这段循环要怎么纠正?

$sa='select * from pql_spices_class order by id asc';<br />      $ra=mysql_query($sa);<br />	  $i=1;<br />	  while($rsa=mysql_fetch_array($ra,MYSQL_ASSOC))<br />      {<br />		  //echo $rsa['classname'].",".$rsa['id']."<br />";<br />		  $cid = $rsa['id'];<br />		  $resf=mysql_query('SELECT * FROM `pql_spices` where classid='.$cid.' ORDER BY id DESC');<br />          while($rsf=mysql_fetch_array($resf)) <br />          {<br />             $Prices+=$rsf['Price'];<br />          }<br />		  echo $i."、".$rsa['classname'].":".$Prices."元,";<br />		  $i++;<br />	  }
Copy after login


一个分类数据表pql_spices_class:有 分类一、分类二、分类三、……每个分类有对应的ID
一个列表数据表pql_spices:有商品名称、价格、分类ID、分类名称

要把pql_spices表里的价格按分类分别统计价格总价,但我这段代码的结果是:分类一统计对了,到了分类二确是分类一的总和加上分类二的总和,到了分类三确是分类二+加上分类三的总和,以此类推,每一次新分类的统计都会自动加上 上一次分类的统计总和,这就不对了。

请问代码要怎么写,才能准确得到各自分类的统计。不知道这样提问大家能不能明白我要问的意思。
------解决思路----------------------
你的 $Prices 总是累加没有清0,自然就是现在的结果

再说一个分组求和的查询指令就可完成的事情,为何要用循环累加完成?
------解决思路----------------------
$sa='select * from pql_spices_class order by id asc';

      $ra=mysql_query($sa);

  $i=1;

  while($rsa=mysql_fetch_array($ra,MYSQL_ASSOC))

      {
[color="red"]$Prices=0;//这里清零[/color]
  //echo $rsa['classname'].",".$rsa['id']."
";

  $cid = $rsa['id'];

  $resf=mysql_query('SELECT * FROM `pql_spices` where classid='.$cid.' ORDER BY id DESC');

          while($rsf=mysql_fetch_array($resf)) 

          {

             $Prices+=$rsf['Price'];

          }

  echo $i."、".$rsa['classname'].":".$Prices."元,";

  $i++;

  }

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template