0

I want to run two seperate foreach loops on the one page, but only write my SQL once. For example see the below code, only the ul with the id of first runs, the second ul is empty.

    <?php
        $mylist = 'SELECT * FROM myTable';
        $showlist = $pdo->prepare($mylist);
        $showlist->execute();
    ?>  
    <ul id="first">
        <?php foreach ($showlist as $rowid):;?>
            <li><?php echo $rowid['id'] ?></li>
        <?php endforeach; ?>  
    </ul>
    <ul id="second">
        <?php foreach ($showlist as $rowname):;?>
            <li><?php echo $rowname['name'] ?></li>
        <?php endforeach; ?>  
    </ul>

I thought renaming the as would allow me to use it again but this doesn't seem to be the case? What is the best approach here?

2
  • 1
    Possible duplicate of stackoverflow.com/questions/278259/… Commented Aug 13, 2013 at 10:26
  • @AlmaDoMundo fair call re being a duplicate. I think the two answers here are better than the other site though in terms of giving an example of how to get this working? Commented Aug 13, 2013 at 10:37

2 Answers 2

2

try:

<?php
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
$result = $showlist->fetchAll();

foreach ($result as $rowid) {
    // do stuff
}

foreach ($result as $rowname) {
    // do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

1

You'd need to stack your elements in an extra array first:

$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();

$rows = array();

foreach($showlist as $row) {
    array_push($rows, $row);
}

echo "<ul>";
foreach($rows as $row) {
    echo "<li>".$row['id']."</li>";
}
echo "</ul><ul>";
foreach($rows as $row) {
    echo "<li>".$row['name']."</li>";
}
echo "</ul>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.