Hashey100
Hashey100

Reputation: 984

how to store json_encode results in a table

I have a database which works by displaying first and last_names of all employees in the database, i can display it but when it displays, it's not formatted. I want to try and put the results in a table but I'm not sure how I would.

I thought I would have to echo json_encode(echo.<td>$posts</td>) or something like that

 <?php foreach($query as $row): ?>
   <tr> 
   <td>
        <?php $arr = array(

                        'first_name' => $row->first_name,   
                        'last_name' => $row->last_name,

                        ); ?>
    <?php  $posts[] = $arr;?>

    </tr>
    <?php endforeach; ?>
    <?php echo json_encode($posts);?>

This is how its displayed now

[{"first_name":"Georgi","last_name":"Facello"},    
{"first_name":"Georgi","last_name":"Atchley"}]

Upvotes: 0

Views: 961

Answers (3)

aziz punjani
aziz punjani

Reputation: 25786

<table>
<thead> 
   <th> First Name </th> 
   <th> Last Name </th> 
</thead> 
<tbody> 
   <?php foreach($query as $row): ?>
      <tr>
         <td> <?php echo $row->first_name ?> </td> 
         <td> <?php echo $row->last_name ?> </td>
      </tr>
   <?php endforeach; ?>
</tbody> 
</table> 

Upvotes: 1

user1703809
user1703809

Reputation:

You're gonna have to build the table 'by hand'. Like this:

<table>
<?php foreach($query as $row): ?>
   <tr> 
   <td>
     <?php echo $row->first_name; ?>
   </td>
   <td>
     <?php echo $row->last_name; ?>
   </td>
   </tr>
<?php endforeach; ?>
</table>

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191789

Nothing is written between your <tr> and such .. you are just assigning to posts and then printing it out as JSON after the fact which makes no sense.

<?php foreach... ?>
<tr>
   <td>
      <?php echo $row->first_name ?>
   </td>
   <td>
      <? php echo $row->last_name ?>
   </td>
</tr>
<?php endforeach ?>

Upvotes: 1

Related Questions