Home > Back-end >  Is it possible to re-open a closed while in php?
Is it possible to re-open a closed while in php?

Time:09-18

I'm building an admin page dashboard and I have three widgets. So I have a while loop that gather my database content and displays it inside a widget, such as my posts data, my users data and others. I have to close my loop so the code stays inside the widget :

<?php while($data = $posts->fetch())
                    { 
                    ?>
                        <tr >
                            <th scope="row"><?=htmlspecialchars($data['id'])?></th>
                            <td><?=htmlspecialchars($data['title'])?></td>
                            <td><?=htmlspecialchars($data['creation_date_fr'])?></td>
                            <td><a href="index.php?action=editPost&id=<?=$data['id']?>">Éditer l'article</a></td>
                            <td><a href="index.php?action=deletePost&id=<?=$data['id']?>" ><ion-icon name="trash"></ion-icon></a></td>
                        </tr>
                    <?php
                    }
                    ?>

But can I re-open my while loop so I can use the same data for another widget after another HTML section ? Because the while loop is repeating the code for each row in my data base...

<?php while ($data = $posts->fetch())
            {
            ?>
            <?php
            // Code inside here to display some others posts'data...
            }
            $posts->closeCursor();
            ?>   

So my final render would be something like this :

//First part of HTML Code...

<?php while($data = $posts->fetch())
{
?>

<tr >
<td>...
<td>...
<td>...
<td>...
<td>...

<?php
// end of the while loop

}
?>

// Another part of HTML code...
//then

<?php while($data = $posts->fetch))
{
?>

//Display something else

<?php

//Close again the while loop
}
$posts->closeCursor();
?>

Of course this doesn't work... Any ideas ?

CodePudding user response:

One way to do this more easily would be with php templates. The idea is to use some library (e.g. Twig) to render pages that use special syntax and can include php code or variables with html css. You could also just echo the html content from php block.

CodePudding user response:

The code in the question mixes some bussiness logic and presentation logic. If these two parts were separated, then "reopening" would not be needed.

Just fetch all the data to a variable (an array) and pass the variable to the template. You can loop over the same array as many times as you require.

If there's a reason not to cache the data in a variable (however, in your case I can't see any such a reason), one can use some more advanced techniques like iterators - pass an object implementing the Iterator interface to the template; then each foreach will "reopen" the iterator (for more details please see https://www.php.net/manual/en/iterator.rewind.php).

  • Related