Limit number of rows to return

I’m using the following query to get menu_items related to a certain menu:

$sql = "SELECT *
          FROM menu_items
      ORDER BY item_id";
                    
$stmt = $this->pdo->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

$kaart_items = array();
foreach ($result as $row) {
    if (!isset($kaart_items[$row['menu_id']])) {
        $kaart_items[$row['menu_id']] = array();
    }
    $kaart_items[$row['menu_id']][] = $row;
}
return $kaart_items;

and in my template I have:

<div class="row pakketten">
    <?php foreach ($menus as $menu): ?>
    <div class="pakket os-animation" data-os-animation="fadeInUp" data-os-animation-delay="0.5s">
        <img src="/images/pakket_fotos/<?php echo $menu['menu_foto']; ?>">
        <h3><?php echo $menu['menu_naam']; ?><span><?php echo $menu['menu_prijs']; ?></span></h3>
        <ul class="items">
            <?php foreach ($kaart_items[$menu['menu_id']] as $value): ?>
            <li><?php echo $value['item']; ?></li> 
            <?php endforeach; ?>
        </ul>
    </div>        
    <?php endforeach; ?>    
</div>

This works fine but what I actually need is to limit the number of menu_items to 5. I tried do the limitation within the query:

ORDER BY RAND()
           LIMIT 5

But then I get the following errors:

 Notice: Undefined offset: 2 in C:\wamp\www\Bbq-man\private\templates\partials\menus.php on line 15
Notice Undefined offset: 3 in C:\wamp\www\Bbq-man\private\templates\partials\menus.php on line 15
Notice: Undefined offset: 4 in C:\wamp\www\Bbq-man\private\templates\partials\menus.php on line 15

There are 4 menus in total and with the limitation as above it just limit the complete table where it should limit for each menu

I hope I made myself clear.

Thank you in advance

i think you need to define offset in limit clause

replace

ORDER BY RAND() LIMIT 5

with

ORDER BY RAND() LIMIT 0,5

it might remove your undefined offset errors

vineet

Hi vinpkl. Thanks for the responce. I think I didn’t make myself clear enough. In total I have four menus (basic, popular, DeLuxe and Veggie) In the output for each menu I want to show 5 items. The way I tried it I was just limiting the table for 5 items so in the output the first menu was indeed populated and the other three weren’t. I think I should do the limitation within or after the foreach llop but have no idea how to do that

I have this one solved using array_slice in the template:

<?php foreach(array_slice($kaart_items[$menu['menu_id']], 0, 5) as $value ): ?>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.