Welcome Guest, Not a member yet? Register   Sign In
Process result from DB in Controller
#1

[eluser]SniffTheGlove[/eluser]
Hello,

Struggling to get my head around the DB access code in CI and need some help.

I am running a function in my model to extract a single value from a MySQL table.

Code:
function get_Geo_Location_Latitude()
{
    $query = $this->db->query('SELECT geo_defaults_value FROM geo_defaults WHERE geo_defaults_descriptor = "Latitude" ');
    if ($query->num_rows() == 0)
    {
        //show_error('Database is empty!');
    }
    else{  
        return $query->result();
    }
}

In the controller I can assign the result to a variable
Code:
$main_var['Latitude'] = $this->model_home->get_Geo_Location_Latitude();
that can be passed to the view which works fine but I want to assign the actual value from the query (which will be 47.345612) to a variable called $latitude that I can work with in the controller but I can not see how to access the variable as the result returns an object, if I use return $query->result_array(); then an array is returned but I still can not get access to it. I have tried many ways but stumped.

Any ideas?
#2

[eluser]mrpaco85[/eluser]
If you're looking for a single value, you might want to use $query->row() instead. Otherwise, you will have to iterate get_Geo_Location_Latitude() in order to get at a specific value. The row() function will return an object with your selected columns as attributes of that object.

In your model:
Code:
function get_Geo_Location_Latitude()
{
    $query = $this->db->query('SELECT geo_defaults_value FROM geo_defaults WHERE geo_defaults_descriptor = "Latitude" ');
    if ($query->num_rows() == 0)
    {
        //show_error('Database is empty!');
    }
    else{  
        $row = $query->row();
        return $row->geo_defaults_value;  //This is how you get a single value
    }
}

In your controller:
Code:
$latitude = $this->model_home->get_Geo_Location_Latitude();

$latitude now has the value you are looking for.


Also, see http://ellislab.com/codeigniter/user-gui...sults.html for more information on generating query results.




Theme © iAndrew 2016 - Forum software by © MyBB