No. of rows returned and sum of row field
3 posts by 2 authors in: Forums > CMS Builder
Last Post: April 29, 2014 (RSS)
By zaba - April 29, 2014
Hi
I need to know how may rows a given query returns and also I need to calculate the sum of a given field in a row.
See below... thanks in advance
<?php session_start();
$session=session_id();
// load records from 'basket'
list($basketRecords, $basketMetaData) = getRecords(array(
'tableName' => 'basket',
'loadUploads' => false,
'allowSearch' => false,
'where' => "session='$session'",
));
?>
<table>
<tr>
<td>Course</td><td>Price</td></tr>
<?php foreach ($basketRecords as $record): ?>
<tr>
<td><?php echo htmlencode($record['course']) ?></td><td><?php echo htmlencode($record['price']) ?></td>
</tr>
<?php endforeach ?>
</table>
<-- How can I calculate the number of rows returned? (i need this figure in order to calculate a discount) -->
<-- How can I get the sum total for the $record['price'] field of all returned rows? -->
By Chris - April 29, 2014
Hi zaba,
You can count the $basketRecords array with count():
There were <?php echo count($basketRecords); ?> record(s) returned.
The simplest way to sum a field is to use a variable and a foreach loop:
<?php
$sum = 0;
foreach ($basketRecords as $record) {
$sum = $sum + $record['price'];
}
?>
The total price is: <?php echo $sum ?>
Does that help?
Chris