user991830 February 2016

sql/php to grab the minimum & maximum from multiple table entries

I hope the below makes sense...

I'm grabbing all of the children records using the following (another script does the getChildRecords):

<?php $children = $this->item->getChildRecords(); ?>

I am then doing a foreach to grab all of the children house ID's:

<?php
foreach ( $children as $i => $id )
  {
    $house = JTable::getInstance('house', 'MyTable');
    $house->load($id);
?>

Then I am pulling back the number of rooms for each child house entry:

<div><?php $house->rooms; ?></div>

And finishing off my foreach:

<?php } ?>

The children table may contain the following room entries:

ID - 22 Rooms - 1 | ID - 22 Rooms - 5 | ID - 22 Rooms - 2 | ID - 22 Rooms - 3

Question:

What I want to show is the Min to Max number of rooms from all of the child entries.

i.e. 1-5

Answers


Fuujin February 2016

Do you even need the single children entries on that page? Or is it an overview? If you don't need the single entries you could create a function like

public function getMinAndMaxRooms() {
    $con=mysqli_connect("localhost","my_user","my_password","my_db");
    $result mysqli_query($con,"SELECT id, MIN(rooms), MAX(rooms) FROM rooms GROUP BY id");
    if ($result !== false) {
        return $result->fetch_all(MYSQLI_NUM);
    }
    return array();
}

And in your template cycle through it:

<?php foreach ($this->item->getChildRecords() as $child) : ?>
<?php echo $child[0) . ': ' . $child[1] . '-' - $child[2] ?>
<?php endforeach; ?>

Post Status

Asked in February 2016
Viewed 1,035 times
Voted 9
Answered 1 times

Search




Leave an answer