Page 1 of 1

Fetching data into array for performing calculations

Posted: Thu Jun 18, 2009 11:48 am
by atyler
I realize that this has probably been answered somewhere on this forum and elsewhere, but I can't seem to find exactly what I'm looking for.

I am reading multiple values (rows) from one field in a database table. I want to be able to read those values into an array that I can use to perform calculations. However when I fetch the results into the array, the array seems to hold only one row at a time.

In order to assign the values to independent variables that I can calculate with, I can use something like the code below, but I am certain that there is a better way. Especially considering there may be 100s of rows, the switch/case method is a non-option.

I just don't know what that better way is.

Thanks in advance for your input!
AT

Code: Select all

$sql = "SELECT fieldName FROM table ORDER BY id DESC LIMIT 4";
    $res = mysql_query($sql);
 
 
while ($array = mysql_fetch_array($res)){
        $value = $array['fieldName'];
        $i++;
 
    switch ($i){
            case 1:
                $val1 = $value;
            case 2:
                $val2 = $value;
            case 3:
                $val3 = $value;
            case 4;
                $val4 = $value;
        }

Re: Fetching data into array for performing calculations

Posted: Thu Jun 18, 2009 12:06 pm
by jgadrow
Each time your while () loop executes, you're assigning a new value to the row. What you need to do is define $value as an array prior to being utilized in the while () loop.

Code: Select all

// perform query
$sql = "SELECT fieldName FROM table ORDER BY id DESC LIMIT 4";
$res = mysql_query($sql);
 
// setup array to contain values
$values = array ();
 
// obtain row and add to array
while ($row = mysql_fetch_row ($res))
{
 $value [] = $row [0];
}

Re: Fetching data into array for performing calculations

Posted: Thu Jun 18, 2009 12:23 pm
by atyler
Awesome!

Thanks a ton!

AT