【问题标题】:How to count total number of rows in a view which retrieved from database如何计算从数据库中检索的视图中的总行数
【发布时间】:2020-06-06 05:38:55
【问题描述】:

我想在表格中显示一些列。另外,要计算表中显示的总行数。我尝试了一些方法,如果这是正确的方法或有其他更好的方法,请您帮助我。

我的模特

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>

输出显示正确,但我只想知道是否有更好的方法来做到这一点。

【问题讨论】:

    标签: php html mysql codeigniter


    【解决方案1】:

    恕我直言,您无需以这种方式计算您的物品 - 试试这个

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

    【讨论】:

      【解决方案2】:

      我们可以更进一步,在数组上添加一些检查(在这种情况下这是多余的,因为模型中使用的 ->result_array() 将始终返回一个数组)并使用 php 的 if () ;万一;嵌入 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,但无论如何它都会这样做。所以一切看起来都很安全。

      我在条件句中有你的&lt;tbody&gt; 标签,所以如果它们需要在外面,你可以修复它以适应。

      【讨论】:

      • 你可能是对的 - 但在这种情况下,不需要以这种方式检查它,因为 Codeigniters result_array 方法总是返回一个数组 - 如果没有结果,你会得到一个空数组跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 2014-05-24
      • 1970-01-01
      相关资源
      最近更新 更多