Welcome Guest, Not a member yet? Register   Sign In
Retrieve single variables from a database
#1

[eluser]m40[/eluser]
In WordPress you can retrieve single variables from a database. It looks like:
Code:
$name = $wpdb->get_var("SELECT name FROM $wpdb->terms WHERE term_ID=4");

Is there anything similar in CI?
#2

[eluser]jedd[/eluser]
By extending the CI Model - I've put a couple of calls into MY_Model that give me something similar to this.

Within my models I can now do things like this:
Code:
function  get_forum_name_by_forum_id ( $forum_id = 0)  {
    $query_string = "SELECT
                        name
                    FROM
                        forum
                    WHERE
                        id=". $forum_id ;

    return $this->my_get_field  ($query_string, "name");
    }  // end-method  get_forum_name_by_forum_id ()

Within MY_Model:
Code:
function  my_get_field  ( $query_string = NULL , $field = NULL )  {
    if ( (! $query_string) OR (! $field) )
        echo "YOU HAVE FIALED";

    $query = $this->db->query ($query_string);

    if ($query->num_rows() != 1)
        return FALSE;

    $row = $query->row_array();
    $query->free_result();
    return $row[$field];
    }

I've only recently started experimenting with this approach, so while I'm finding it handy (at least, handier than things were before) I'm not yet sure if it's the best way to go, and I know that my naming might need a bit more thought.

Currently I have three functions in MY_Model - the my_get_field() as shown, as well as my_get_row and my_get_rows - those two basically just handle the emptiness problem, returning FALSE if nothing's really there, and freeing the result. It saves a smidgen of repetition, I find.
#3

[eluser]n0xie[/eluser]
You could take a look here: http://www.phpfour.com/blog/2008/07/exte...deigniter/.

Or if you want to do it manually you could use method chaining. Something like this:
Code:
$name = $this->db->query('SELECT name FROM $wpdb->terms WHERE term_ID = 4')->row('name');
#4

[eluser]m40[/eluser]
I love the method chaining approach. Thanks for all suggestions!
#5

[eluser]Dam1an[/eluser]
m40, just so you know, method chaining only work with PHP5, so if you're on PHP, you might ecounter some errors, but I'm sure you won;t as all the cool kids are on PHP5 Wink
#6

[eluser]m40[/eluser]
Oh yeah, I'm one of the cool kids Wink Thanks for the warning though!




Theme © iAndrew 2016 - Forum software by © MyBB