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}
        <h4>{$title}<h4>
        <h6>{$submission_date}</h6>
        <p>{$instructions}</p>
        <p>{$category}</p>
    {else}
        You are currently not signed in.
    {/if}

</div>

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}
            <h4>{$value.title}<h4>
            <h6>{$value.submission_date}</h6>
            <p>{$value.instructions}</p>
            <p>{$value.category}</p>
        {/foreach}
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵