In Codeigniter, how can I check for results from SQL query to database?

Posted on 2010-03-29
Medium Priority
Last Modified: 2013-11-10
In my database model, I have a function that accepts an SQL statement as a parameter and returns the results in what I believe is an array of objects.

But if no records are found, it is returning "0" instead of an array of objects.

I know this can't be right because I get syntax errors when I try to test the returning results when no records are found.  

What would be the proper way to handle this so that the controller can check to see if any results are returned before calling the view?

Code is attached.

function Fetch_query($sql)
   $results = $this->masters->query($sql);
      $results = $results->result_array();
      return $results;
      return "0";

Open in new window

Question by:lthames
LVL 45

Accepted Solution

Chris Stanyon earned 2000 total points
ID: 29029320
Try something like the following.

You can then check whether the array is empty or not and act accordingly.

//Your model
function Fetch_query($sql)
    $query = $this->db->query($sql);
    return $query->result_array();

//Your controller.
$myrecords = $this->myModel->Fetch_query("select * from wherever");

if ($myRecords)
    //we have records
    //we don't have records so do something else.

Open in new window


Author Closing Comment

ID: 31708593
Very helpful, I was able to complete the page with your help.

thank you!

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

600 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question