我正在使用php / mysql和smarty(php模板生成器) . 我正在循环一个SQL查询并获取数据显示在.tpl文件上 .
$query = "SELECT * from recipes";
$result = mysqli_query($db_server, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// assign user information to template
$tpl->assign('title', $row['title']);
$tpl->assign('submission_date', $row['submission_date']);
$tpl->assign('instructions', $row['instructions']);
$tpl->assign('category', $row['category']);
}
} else {
echo "0 results";
}
我的HTML:
<div class="content">
{if $signedin}
<h4>{$title}<h4>
<h6>{$submission_date}</h6>
<p>{$instructions}</p>
<p>{$category}</p>
{else}
You are currently not signed in.
{/if}
</div>
问题是这只显示最近的条目,我试图显示数据库中的每个条目 .
我的循环出了什么问题?
我在每个$ tpl-> assign之间放置了echo,它循环并显示所有数据,所以我想知道这是否是Smarty问题 .
1 回答
就像我在评论中所说的那样,你只获得最后一行值的原因是因为循环中的每次迭代都会覆盖这些值 .
你可以做的一种方法是创建一个容器,然后使用你的
while
循环并将它们全部放在首位 . 完成之后,然后在模板内部->assign()
进行循环演示和逻辑以及其他需要做的事情 .这是基本的想法: