php - Manipulate PDO Object Results Into a Template


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


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


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

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


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.





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 makeTemplates, you should take a look at some templating-languages likeTwig.

People are also looking for solutions to the problem: php - Laravel Thujohn Twitter bad authentication error


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.