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

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

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
lthamesAuthor Commented:
Very helpful, I was able to complete the page with your help.

thank you!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.