php - very slow to show result -
i have windows7 system wamp 2.4 running simple php code
for ($year = 2004; $year <= 2015; $year++){ ($month = 1; $month <=12; $month++){ mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select db"); $result = mysql_query("select sum(weight) lab year(date)=$year , month(date)= $month") or die(mysql_error()); while ($rows = mysql_fetch_array($result)) { $weight = $rows['sum(weight)']; ${'mes'.$month}=$weight; $weight3=$weight+$weight3; $weight=0; } } echo $year, " total - ", $weight3, "<br>"; echo $mes1, ", ", $mes2, ", ", $mes3, ", ", $mes4, ", ", $mes5, ", ", $mes6, ", ", $mes7, ", ", $mes8, ", ", $mes9, ", ", $mes10, ", ", $mes11, ", ", $mes12, "<br>"; $weight3=0; } my database 400000 rows , reason takes 40 seconds shows result. if same query (year year) in mysql takes less second.
is there wrong code slowsdown query? or wamp related problem?
thanks help!
final code
mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select db"); $result = mysql_query("select year(date), month(date), sum(weight) lab date between '2004-01-01' , '2015-12-31' group year(date), month(date)"); while ($rows = mysql_fetch_array($result)) { echo $rows ['year(date)']," ", $rows ['month(date)']," ",$rows['sum(weight)']; echo "<br>"; }
that code incredibly inefficient. connect db 11 years * 12months = 132 times. loops unecessary too. why not in query?
select year(datefield), month(datefield), sum(weight) youtable datefield between '2004-01-01' , '2015-12-31' group year(datefield), month(datefield)
Comments
Post a Comment