Forum Moderators: coopster
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;
}
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
UPDATE: Just discovered count recursive. Nice. This will work.
tx
Adam