PDO Fetchall, fetch, while and foreach loop only selects 1 row

i have a table like this

id  name           cat_slug
(1, 'Electronics', 'Cellphones and Accessories'),
(2, 'Electronics', 'Computers and Accessories'),
(3, 'Electronics', 'House Appliances'),
(4, 'Electronics', 'Miscellaneous'),
(5, 'Furniture', 'Office Furniture'),
(6, 'Furniture', 'House Furniture'),
(18, 'Clothing and Handbags', 'Handbags, Wallets and Purses');

and my php code is like this

$acces = 'Electronics';
                
$conn = $pdo->open();
try{
    $stmt = $conn->prepare("SELECT `id`, `cat_slug`FROM mall_category WHERE name = :acces");
    $stmt->execute(['acces' => $acces]);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($result as $row) {
        $categ = $row['cat_slug']; 
    }                 
} catch(PDOException $e){
    echo "There is some problem in connection: " . $e->getMessage();
}
    
$pdo->close();

I created a dropdown menu

<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Electronics</a>
    <ul class="dropdown">
      <li><a href='shopping.php?category=<?php echo $row['cat_slug']?>'><?php echo $categ; ?></a></li>
    </ul>
</li>

and want all electronics as list in dropdown. If i use foreach loop, whileloop, or fetchAll i get only 1 row
I tried searching the entire web, stackoverflow and couldn’t find a working solution. please help

>Solution :

You need to put the dropdown choices in the loop.

<?php
$acces = 'Electronics';
                
$conn = $pdo->open();
try{
    $stmt = $conn->prepare("SELECT `id`, `cat_slug`FROM mall_category WHERE name = :acces");
    $stmt->execute(['acces' => $acces]);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e){
    echo "There is some problem in connection: " . $e->getMessage();
}
$pdo->close();

?>
<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Electronics</a>
    <ul class="dropdown">
    <?php foreach ($result as $row) { ?>
      <li><a href='shopping.php?category=<?php echo $row['cat_slug']?>'><?php echo $categ; ?></a></li>
    <?php } ?>
    </ul>

</li>

Leave a Reply