Forum Moderators: coopster

Message Too Old, No Replies

subsets of data from a query handle?

         

adamohern

4:15 pm on Nov 21, 2007 (gmt 0)

10+ Year Member


I'm trying to make a script that creates a table with various bits of customizable information at the top, like category totals, a grand total, number of records, etc.

I'm having a problem I don't quite understand. It generates and displays the total correctly, but then doesn't give me the data in my html table. If I disable the call to "generateTotal()", the html table renders fine. Here's my basic code (abridged):

function generateTable($theData){

$html_output = '<p>'.mysql_num_rows($theData).' found, totalling '.generateTotal($theData).' </p></td>'."</tr>\n";

for($x = 0 ; $x < mysql_num_rows($theData) ; $x++){
$row = mysql_fetch_assoc($theData);

$html_output .= bla bla bla //insert all my table row formatting here
}

$html_output .= "</table>";
return $html_output;

}

function generateTotal($theData){

$i=-1;
while($row = mysql_fetch_array($theData)){
$total[$i++] = $row['amount'];
}
$total=array_sum($total);
return $total;
}

sned

5:16 pm on Nov 21, 2007 (gmt 0)

10+ Year Member



The mysql_fetch_array function is moving the current row pointer along the result set.

So, when you call the generateTotal function, the pointer goes all the way to the end of the result set.

Then, when you call the generateTable function, the pointer sees that it's at the end of a set, has nowhere to go, and thus returns nothing.

There's a couple ways to fix this. You can use a mysql_data_seek [us.php.net] to reset the pointer.

Or, (I think this is the better way), you can read the results into an array, and just pass that array to your functions. Something like:

$data_array = array(); 
while($row = mysql_fetch_assoc($theData)){
$data_array[] = $row;
}

// call function with generateTotal($data_array);

function generateTotal($arr){
$total = 0;
$arr_count = count($arr);
for($x = 0; $x < $arr_count; $x++){
$total += $arr[$x]['amount'];
}
return $total;
}

-sned

adamohern

5:49 pm on Nov 21, 2007 (gmt 0)

10+ Year Member



Perfect, just as I suspected. Thanks so much for the quick response!

Adam

adamohern

5:54 pm on Nov 21, 2007 (gmt 0)

10+ Year Member



So this actually brings me to a new question: how do I drill thru an array by row? Say I've got all my data into an array as you suggest; how can I do a loop that will let me grab the values of each row and plug them into html? Sorry to ask such a basic question!

UPDATE: Just discovered count recursive. Nice. This will work.

tx
Adam