2012-08-03 51 views
0

我在codeigniter的视图文件中有以下代码。如何从数组中获得第一个数据

<?php foreach ($records as $rows){?> 
<? echo $rows['product_name']; ?> <br> 
<? } ?> 

我的模型

$this->db->select('*'); 
     $this->db->from('products'); 
     $this->db->order_by('product_name','ASC'); 
     $getData = $this->db->get(''); 
     if($getData->num_rows() > 0) 
     return $getData->result_array(); 
     else 
     return null;  

如果我运行上面的代码中,我得到以下结果

Pepsi 
    Coke 
    Mountain Dew 

我想只显示第一个结果(百事可乐)。你能告诉我怎么做吗?

回答

1

$ records is 数组。您可以指定像

<?=$records[0]['product_name']?> 
0

使用LIMIT告诉DB从数据库中提取唯一的记录数量有限

$this->db->from('products LIMIT 0,1'); 
+0

我无法限制查询,因为我需要其他信息在我的同一个视图文件中。是否可以不限制查询?谢谢:) – 2012-08-03 07:53:34

0

这应该工作:

$query = $this->db->limit(0, 1); 

见文件:http://codeigniter.com/user_guide/database/active_record.html

参见: CodeIgniter Database query limit

+0

我不能限制查询,因为我需要在同一个视图文件中的其他信息。是否可以不限制查询?谢谢 – 2012-08-03 07:53:52

+0

然后你可以在结果上使用'row()'方法,参见:http://stackoverflow.com/questions/4280235/code-igniter-return-only-one-row – 2012-08-03 08:03:35

相关问题