1

I'm attempting to build a news page for my site. At the moment I'm trying to get the page to retrieve all of the rows in the table then split each column into variables and convert the data into a string.

Here's an example of what I mean.

News Post 1:

ID: 1
POST TITLE: Welcome
POST DATE: 03/10/2018 
POST AUTHOR: Administrator
MESSAGE: Lorem.

News Post 2:

ID: 2 
POST TITLE: Goodbye
POST DATE: 03/10/2018
POST AUTHOR: Administrator
MESSAGE: Ipsum.

That's how the data is represented in the table.

I would like to put each column into a variable, so when I put the data into a news box. Each news item displays in the same format. Like a forum. When I retrieve the data from the database it gives this:

array(1) { [0]=> array(10) { ["id"]=> int(1) [0]=> int(1) ["posttitle"]=> string(37) "Welcome" [1]=> string(37) "Welcome" ["postdate"]=> string(10) "2018-10-02" [2]=> string(10) "2018-10-02" ["postauthor"]=> string(27) "Administrator)" [3]=> string(27) "Administrator)" ["message"]=> string(12) "Lorem" [4]=> string(12) "Lorem" } }

And this is the code I currently have:

<?php

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

$pdo->commit();

?>

Any help would be greatly appreciated.

Thanks.

1 Answer 1

1

If you want to remove those indexed duplicates, use this:

$results = $query->fetchAll(PDO::FETCH_ASSOC);

Then your results be:

array(1) { [0]=> array(10) { ["id"]=> int(1) ["posttitle"]=> string(37) "Welcome" ["postdate"]=> string(10) "2018-10-02" ["postauthor"]=> string(27) "Administrator)" ["message"]=> string(12) "Lorem" } }

Read this for better understanding: http://php.net/manual/en/pdostatement.fetchall.php http://php.net/manual/en/pdostatement.fetch.php

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using FETCH_OBJ. Which then only gave id = 1. posttitle = welcome ect...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.