Jas
Jas

Reputation: 63

Adding Array to MySQL Fetch

I'm fetching results from my database (fetchAll), and later encoding it into json.

However, I want to add additional values to it, but I have no idea how to achieve that.

I tried doing this is:

while ($posts = $database->fetchAll()) {
    $posts['additional'] = 'test';
}

But it wasn't working.

The result I'm after is changing the results from this:

[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"}, 
    {"firstName":"Peter", "lastName":"Jones"}
]

to

[
    {"firstName":"John", "lastName":"Doe", "additional":"test"}, 
    {"firstName":"Anna", "lastName":"Smith", "additional":"test"}, 
    {"firstName":"Peter", "lastName":"Jones", "additional":"test"}
]

What should I do? Thanks!

Upvotes: 1

Views: 42

Answers (1)

xdazz
xdazz

Reputation: 160923

Don't use fetchAll and while together.

Then:

$posts = array();
while ($post = $database->fetch()) {
    $post['additional'] = 'test';
    $posts[] = $post;
}

Or:

$posts = $database->fetchAll();
foreach ($posts as &$post) {
  $post['additional'] = 'test';
}

Upvotes: 4

Related Questions