简体   繁体   中英

Codeigniter populate a table from database

I want to populate all the data from my database to a table using <?php foreach; ?> <?php foreach; ?> but I can't get it to work. Please check my code:

controller
$data['query'] = $this->db->query('SELECT * FROM users');
$this->load->view('users_view',$data);

View
<?php foreach ($query->result_array() as $row)
{ ;?>
<tr>
<td><?php echo $row['usrID'];?></td>
<td><?php echo $row['usrName'];?></td>
<td><?php echo $row['usrPassword'];?></td>
</tr>
<?php } ?>
<?php endforeach; ?>

I would reccommend the alternative syntax for your foreach in the view...

It looks like you should be having some syntax errors the way you have it.

<?php foreach ($query->result_array() as $row): ?>
    <tr>
        <td><?php echo $row['usrID'];?></td>
        <td><?php echo $row['usrName'];?></td>
        <td><?php echo $row['usrPassword'];?></td>
    </tr>
<?php endforeach; ?>

EDIT - to point out your syntax issues.

<?php foreach ($query->result_array() as $row)
{ ;?> //<---- semicolon?
<tr>
<td><?php echo $row['usrID'];?></td>
<td><?php echo $row['usrName'];?></td>
<td><?php echo $row['usrPassword'];?></td>
</tr>
<?php } ?>
<?php endforeach; ?> //<--- no need for this when using regular foreach

This first semicolon would be like writing a foreach like this...

foreach ($array as $ele) { ; //<--this would throw an error just like it should above.
    //do stuff
}

Opinion aside from the point of the question

You should be processing your data in the controller and simply sending an array of data to be displayed in the view, not the whole query object.

so...

Controller

$query = $this->db->query('SELECT * FROM users');
$data['users'] = $query->result_array();
$this->load->view('users_view',$data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM