Reputation: 33
I want to display some column in a table. Also, want to count the total number of rows showing in the table. I tried some ways, can you please help me if this is the right way or there are other better ways to do this.
my Model
public function getRentedEquipments($project_id=0){
return $this->db->select('e.*, p.project_id')
->from('equipment AS e')
->join('project AS p', 'p.project_id = e.project_id')
->where('p.project_id', $project_id)
->order_by('eq_name','ASC' )
->get()->result_array();
}
My view
<tbody>
<?php
$total_eq=0;
$count=1;
foreach ($pr_eq as $row) {
?>
<tr>
<th scope="row"><?php echo $count;?></th>
<th scope="row"><?php echo $row['eq_id'];?> </th>
<th scope="row"><?php echo $row['eq_name'];?> </th>
<?php
$total_eq+=$row['eq_id']-1;
$count=$count+1;
}
?>
<button class="btn btn-info"> Number of Equipments: <?php echo $total_eq;?></button>
</tbody>
The output is showing correctly, but I just want to know if there are any better ways to do this.
Upvotes: 0
Views: 1207
Reputation: 5507
We could take this a step further adding in some checking on the array (which is overkill in this case as ->result_array() used in the model will always return an array ) and using php's if () ; endif; functionality which can be more readable with embedded HTML.
<?php
// If we have an array get the count, else its 0
$equipment_count = is_array($pr_eq) ? count($pr_eq) : 0;
// If we have a count > 0 , it must be an array
if ($equipment_count > 0): ?>
<tbody>
<?php foreach ($pr_eq as $row): ?>
<tr>
<th scope="row"><?php echo $count; ?></th>
<th scope="row"><?php echo $row['eq_id']; ?> </th>
<th scope="row"><?php echo $row['eq_name']; ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
<?php endif; ?>
<button class="btn btn-info"> Number of Equipments: <?= $equipment_count; ?></button>
Technically you could have an array which has a 0 count, which will fail executing the foreach, which it will do anyway. So that all seems safe.
I have your <tbody>
tags inside the conditional, so if they need to be outside, you can fix it to suit.
Upvotes: 0
Reputation: 5439
imho there is no need for counting your items in that way - just try this
<tbody>
<?php
foreach ($pr_eq as $row)
{
?>
<tr>
<th scope="row"><?php echo $count;?></th>
<th scope="row"><?php echo $row['eq_id'];?> </th>
<th scope="row"><?php echo $row['eq_name'];?> </th>
</tr>
<?php
}
?>
</tbody>
<button class="btn btn-info"> Number of Equipments: <?= count($pr_eq);?></button>
Upvotes: 1