duangelin7513 2018-10-03 10:18
浏览 53
已采纳

将PDO对象结果操作到模板中

I'm making a news page that will update everytime an admin adds a row into the 'news' table. The rows are as follows:

ID, POSTTITLE, POSTDATE, POSTAUTHOR, MESSAGE

I have created a foreach loop that takes all of the data retrieved from that table and takes the data from the nested array:

<?php

$pdo->beginTransaction();
$query = $pdo->prepare("SELECT * FROM news");
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);


foreach($results as $row) {
    foreach($row as $key => $value) {
        dump( $key . " = " . $value);
    }
}

$pdo->commit();
?>

This outputs this data:
(Which is all of the data inside of the table)

"id = 1"
"posttitle = Welcome To Universal Link Media Group"
"postdate = 2018-10-02"
"postauthor = Ethan (Super Administrator)"
"message = Dummy Text. "

Now here's my question. I want to create a template for each post. So they are uniform. Each post will have a 'title' field, a 'date' field, a 'author' field ect... and I want to put the values from the table into the fields.

It will look something like this:

TITLE: $posttitle
AUTHOR: $postauthor
DATE CREATED: $postdate
MESSAGE: $message

And I'd like it to be dynamic, so it doesn't matter how many rows are in the table, there will always be a template post with the posts data inside of it.

Any help would be greatly appreciated, been stuck on this issue for quite a while.

Thanks!

  • 写回答

1条回答 默认 最新

  • duancong2965 2018-10-03 10:44
    关注

    To get your desired output you just need to change your loop to this:

    foreach($results as $row) {
      echo 'TITLE: ' . $row->posttitle . '<br>';
      echo 'AUTHOR: ' . $row->postauthor . '<br>';
      echo 'DATE CREATED: ' . $row->postdate . '<br>';
      echo 'MESSAGE: ' . $row->message . '<br>';
    }
    

    If you really want to make Templates, you should take a look at some templating-languages like Twig. https://twig.symfony.com/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄