Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading