khejduk
khejduk

Reputation: 309

Displaying 0 results in CodeIgniter query

I feel like this is a stupid question, but I cannot find good documentation that explains what I am looking for.

If I query the database in my Model, and pass the results array to my View, where do I state that if there are 0 results print "There are no results to display?"

Upvotes: 4

Views: 19746

Answers (3)

adidasadida
adidasadida

Reputation: 31

Probably best done in the view. Assuming you're not using any template engines,

<?php if ($result->num_rows() > 0): ?>
  // do something...
<?php else: ?>
  <p>There are no results to display</p>
<?php endif; ?>

Upvotes: 0

Gabriel
Gabriel

Reputation: 1900

You can try...

$query = $this->db->query("YOUR QUERY");

$a = $query->result_array();

if(count($a) > 0){
  foreach ($a as $row)
  {
    //....
  }
}

I recommend you read this link http://codeigniter.com/user_guide/database/index.html

Upvotes: 2

Colin Brock
Colin Brock

Reputation: 21565

If you want to display text to the user, that's probably best done in the view.

Assuming you are passing the result() array to the view, you can check whether it's empty or not (i.e. has no records):

if(empty($query->result())){
    // no records to display
} else {
    // records have been returned
}

Otherwise, you can check via the num_rows() method if you're dealing with the db object as a whole (and not just result()):

if($query->num_rows() > 0){
    // records have been returned
} else {
    // no records
}

Upvotes: 8

Related Questions