Codeigniter:如何检测查询结果的第一行

时间:2016-09-26 06:42:14

标签: codeigniter

我的view如下所示。

<div class="carousel-inner">
    <?php 
        foreach($news_data as $nws){
    ?>
    <div class="item **If this is the first row, then echo active**"> 
        <div class="col-md-12 news-item" style="padding-left: 0;">
            <p><?php echo $nws->news_desc; ?></p>
        </div> 
    </div>
    <?php } ?>
</div>

型号:

function get_news_update()
{
    $this->db->select('news_desc');
    $this->db->from('news');
    $this->db->where('stat', '1');
    $this->db->order_by('id', 'desc');

    $query = $this->db->get();
    return $query->result();
}

请参阅<div class="item。如果它是query result的第一行,那么它将是item active

怎么做?

4 个答案:

答案 0 :(得分:2)

修改你的观点:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="message" placeholder="Enter Message" >
<br>
<button id="showBtn">Show Message</button>

<p>
  <h3>Console Here</h3>
<div id="console"></div>
</p>

答案 1 :(得分:1)

这是您更新的代码

       <div class="carousel-inner">
        <?php 
            $i = 0;
            foreach($news_data as $nws){
             // it should be $i. not $i%2 right ?
             if($i == 0) 
            {
                $class="item active";
             }
              else
{
$class = "item";
}
        ?>
        <div class="<?php echo $class;  ?>"> 
            <div class="col-md-12 news-item" style="padding-left: 0;">
                <p><?php echo $nws->news_desc; ?></p>
            </div> 
        </div>
        <?php $i++; } ?>
    </div>

答案 2 :(得分:0)

据我所知,您正在寻找以下代码。如果不能正常工作,请告诉我。

function get_news_update()
{
    $this->db->select('news_desc');
    $this->db->from('news');
    $this->db->where('stat', '1');
    $this->db->order_by('id', 'desc');

    $query = $this->db->get();
    return $query->first_row();
}

答案 3 :(得分:0)

您可以使用row()函数,它始终返回第一个结果。 Model.php

function get_news_update(){
  $this->db->select('news_desc');
  $this->db->from('news');
  $this->db->where('stat', '1');
  $this->db->order_by('id', 'desc');
  $query = $this->db->get();

   //check if exist
  if (isset($query->row())){
        return $query->row();
  }
}

有关更多信息,请参阅here

View.php

<div class="carousel-inner">
    <div class="item **If this is the first row, then echo active**"> 
        <div class="col-md-12 news-item" style="padding-left: 0;">
            <p><?php echo $nws->news_desc; ?></p>
        </div> 
    </div>
</div>