dsbruqxgt820011351 2018-02-08 01:13
浏览 151

PHP,mySQL和Smarty模板。 while循环只显示1个数据库条目

i'm using php/mysql with smarty (php template generator). I'm looping through an sql query and getting the data to display on the .tpl file.

$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";

my html:

<div class="content">
    {if $signedin}
        You are currently not signed in.


The problem is that this is only displaying the most recent entry and i'm trying to display every entry in the database.

What's wrong with my loop?

I have placed echo in between each $tpl->assign, and it loops and displays all data, so i'm wondering if this is a Smarty issue.

  • 写回答

1条回答 默认 最新

  • duanhu7615 2018-02-08 01:24

    Just like what I've said in the comments, the reason why you're only getting the last row value is because every iteration inside your loop, the values gets overwritten.

    A way that you can do is to create a container, then use your while loop and put them all inside first. After you're done, then ->assign() it inside the template and make your loop presentation and logic and other stuff that you need to do.

    Here's the basic idea:

    // Backend
    $data = array(); // initialize a simple container
    $query = "SELECT * from recipes";
    $result = mysqli_query($db_server, $query);
    if ($result->num_rows > 0) {
        // fetch rows
        while($row = $result->fetch_assoc()) {
            $data[] = $row; // push them inside
    // assign user information to template
    $tpl->assign('values', $data);
    // Front end
    <div class="content">
        {foreach from=$values key=k item=value}
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥30 informer时间序列预测
  • ¥20 SSR引物多态性分析
  • ¥15 大漠插件在Win11易语言注册调用和免注册灵异事件,VS上注册调用完全没问题
  • ¥15 Addressable缓存机制做热更新的问题
  • ¥15 微信开发者工具vant组件
  • ¥15 iPhone iCloud云盘资料删除,MAC丢失50多G桌面资料
  • ¥20 希望各位学长可以给我答疑
  • ¥20 Linux实现: 客户端(cli01)通过TCP(或UDP)连接到聊天服务器(serv)进行聊天。
  • ¥15 (标签-matlab|关键词-m3)
  • ¥20 自制cifar10数据集,生成的batch缺少key:b