Issue
This Content is from Stack Overflow. Question asked by wlvlm
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 class="row posts">
<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']?>" class="deletePost"><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 class="...">
<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 ?
Solution
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.
This Question was asked in StackOverflow by wlvlm and Answered by puucee It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.