Welcome Guest, Not a member yet? Register   Sign In
Models: Query returning one result
#1

[eluser]RobbieL[/eluser]
I've started using Models recently, and for the most part they're working a treat, but there is still a few things niggling me. The example I have at the moment is retrieving the smallest ID in a database table. The query looks like this at the moment:

Code:
function getMin($feedID) {
$getMin = $this->db->query("SELECT MIN(id) FROM podcastUpdates WHERE feedID='$feedID'");
return $getMin->result(); }

The query will return only one result, and I want to use that result in the controller that calls the query. Now, because the result will be returned in an array, in order to use the one result it returns do I have to do something like this:

Code:
foreach($getMin as $minID) {
$ID = $minID->MIN(id);}

I usually do the above for queries that are returning a number of results, but if I know the query is only returning one result, isn't their a simpler method to achieve it? Also, not a CI question, but will the "$minID->MIN(id)" work? I get the feeling it won't.

One last thing. The only reason I need the result of the getMin query above to be used in the controller is so it can be passed to another query in the model. Is there away for one query in a model to directly call another?

Cheers. Appreciate any feedback.
#2

[eluser]Michael Wales[/eluser]
A few things here.

result() does not return an array, it returns an object.
result_array() returns an array of all results.
row() is what you are looking for - when you know there is only one row returned.

Definitely check out the User Guide, this is all in there.
#3

[eluser]Noah David[/eluser]
Code:
function getMin($feedID)
{
    $this->db->select('MIN(id) AS id', FALSE);
    $this->db->where('feedID', $feedID);
    $query = $this->db->get('podcastUpdates');
    $row = $query->row();

    return $row->id;
}
    // Call function
    $minID = getMin(2);
    // Echo results, $row->id from function
    echo $minID;

Cheers.
#4

[eluser]RobbieL[/eluser]
Ah, that's exactly what I was looking for. Cheers guys!




Theme © iAndrew 2016 - Forum software by © MyBB