Fetching data into array for performing calculations

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
atyler
Forum Newbie
Posts: 17
Joined: Tue May 26, 2009 10:28 pm

Fetching data into array for performing calculations

Post 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;
        }
User avatar
jgadrow
Forum Newbie
Posts: 22
Joined: Wed Jun 17, 2009 7:56 pm
Location: Cincinnati, Ohio
Contact:

Re: Fetching data into array for performing calculations

Post 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];
}
atyler
Forum Newbie
Posts: 17
Joined: Tue May 26, 2009 10:28 pm

Re: Fetching data into array for performing calculations

Post by atyler »

Awesome!

Thanks a ton!

AT
Post Reply