phpretard Posted May 16, 2008 Share Posted May 16, 2008 I am trying to form an array from thre value of $cost. $result = mysql_query("SELECT * FROM table "); while($row = mysql_fetch_array($result)) { $cost=$row['cost']; } $a=array(SOMTHING HERE); any thoughts? Link to comment https://forums.phpfreaks.com/topic/105914-array-from-while-loop/ Share on other sites More sharing options...
MadTechie Posted May 16, 2008 Share Posted May 16, 2008 Very close <?php $result = mysql_query("SELECT * FROM table "); $cost = array(); while($row = mysql_fetch_array($result)) { $cost[] =$row['cost']; } ?> i normally do this (may not work on yours) <?php $result = mysql_query("SELECT * FROM table "); $cost = array(); while($row = mysql_fetch_array($result)) { $cost[$row['uID']] =$row['cost']; //uID = my unique id } ?> Link to comment https://forums.phpfreaks.com/topic/105914-array-from-while-loop/#findComment-542742 Share on other sites More sharing options...
phpretard Posted May 16, 2008 Author Share Posted May 16, 2008 On that note ... I may be approaching this wrong... I am looking to add all the $cost together. $result = mysql_query("SELECT * FROM table "); while($row = mysql_fetch_array($result)) { $cost=$row['cost']; } $cost has as many values that are in the DB. I just want to take the total of all the rows and echo it out. Link to comment https://forums.phpfreaks.com/topic/105914-array-from-while-loop/#findComment-542743 Share on other sites More sharing options...
MadTechie Posted May 16, 2008 Share Posted May 16, 2008 okay to add it all up, try this <?php $result = mysql_query("SELECT * FROM table "); $cost = 0; while($row = mysql_fetch_array($result)) { $cost=$cost + $row['cost']; } ?> Link to comment https://forums.phpfreaks.com/topic/105914-array-from-while-loop/#findComment-542749 Share on other sites More sharing options...
phpretard Posted May 16, 2008 Author Share Posted May 16, 2008 Thank you for being patient with me. I should have mentioned I would like the total from all the rows outside of the loop. Link to comment https://forums.phpfreaks.com/topic/105914-array-from-while-loop/#findComment-542764 Share on other sites More sharing options...
MadTechie Posted May 17, 2008 Share Posted May 17, 2008 not sure what you mean now.. <?php $result = mysql_query("SELECT * FROM table "); $cost = 0; while($row = mysql_fetch_array($result)) { $cost=$cost + $row['cost']; } echo $cost; ?> or <?php $result = mysql_query("SELECT *, SUM(cost) as total FROM table "); $cost = 0; while($row = mysql_fetch_array($result)) { echo "total = ".$row['total']; } ?> Link to comment https://forums.phpfreaks.com/topic/105914-array-from-while-loop/#findComment-543485 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.