Php 如何计算从数据库检索的视图中的总行数

Php 如何计算从数据库检索的视图中的总行数,php,html,mysql,codeigniter,Php,Html,Mysql,Codeigniter,我想在表中显示一些列。此外,还需要计算表中显示的行总数。我试过一些方法,你能帮助我,如果这是正确的方法或有其他更好的方法来做到这一点 我的模型 public function getRentedEquipments($project_id=0){ return $this->db->select('e.*, p.project_id') ->from('equipment AS e') ->join(

我想在表中显示一些列。此外,还需要计算表中显示的行总数。我试过一些方法,你能帮助我,如果这是正确的方法或有其他更好的方法来做到这一点

我的模型

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();
}
我的看法

<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>

设备数量:
输出显示正确,但我只想知道是否有更好的方法来实现这一点。

我想没有必要用这种方法计算物品的数量——试试这个

<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> 

设备数量:

我们可以进一步增加对数组的一些检查(在本例中这是过分的,因为在模型中使用的->result_array()将始终返回一个数组)并使用php的if();endif;嵌入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>

设备数量:
从技术上讲,您可能有一个计数为0的数组,它将无法执行foreach,无论如何它都会这样做。这样看来一切都安全了


我将您的
标记放在条件中,因此如果它们需要放在外部,您可以根据需要对其进行修复

您可能是对的-但在本例中,没有必要以这种方式检查它,因为Codeigniters
result\u array
方法始终返回一个数组-如果没有结果,您将返回一个空数组