Jump to content

array from while loop


phpretard

Recommended Posts

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
}
?>

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.

 

 

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'];
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.