0

I have the following code in my codeigniter's view file.

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

my model

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

If I run the above code I get the following result

    Pepsi
    Coke
    Mountain Dew

I am trying to show only the first result (Pepsi). Could you please show me how to do that?

black_belt
  • 6,601
  • 36
  • 121
  • 185

4 Answers4

1

$records is an Array. You can specify the index like

<?=$records[0]['product_name']?>
Vladimir Hraban
  • 3,543
  • 4
  • 26
  • 46
0

Use LIMIT to tell the DB to pull only a limited number of records from the database

$this->db->from('products LIMIT 0,1');
asprin
  • 9,579
  • 12
  • 66
  • 119
  • I cannot limit the query, because I need other information in my same view file. Is it possible without limiting the query? Thanks :) – black_belt Aug 03 '12 at 07:53
0

This should work:

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

See doc: http://codeigniter.com/user_guide/database/active_record.html

See also: CodeIgniter Database query limit

Community
  • 1
  • 1
Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113
  • I cannot limit the query, because I need other information in my same view file. Is it possible without limiting the query? Thanks – black_belt Aug 03 '12 at 07:53
  • Then you could use method `row()` on the results, see: http://stackoverflow.com/questions/4280235/code-igniter-return-only-one-row – Maxime Pacary Aug 03 '12 at 08:03
0

reset is another solution to this problem. http://www.php.net/manual/en/function.reset.php

so in the example, $first_element = reset($records);

pgee70
  • 3,707
  • 4
  • 35
  • 41