• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I access the database from a library class?

#1
[eluser]hal10001[/eluser]
I created my own library class, which works fine, but I just can't get connected to the database to run a query. From a function I try to load in the "database" library, but get the following:

Unable to load the requested class: database

This is the basic code:

Code:
class MyClass {

    function myFunction()
    {
        $CI =& get_instance();
        $CI->load->library( 'database' );

        $query = $this->db->query( 'SOME QUERY GOES HERE' );
        return count( $query->result() );
    }
    
}

How do I do this from a library class, and do I need a model, or can I just run the query like normal when using the database class? Thanks!

#2
[eluser]Michael Wales[/eluser]
You were almost on the right track. You are getting the CodeIgniter super object, and you are using it to load the library, but then you fail to use it to actually do anything with the library.

Remember - CI always does things to the super object, not to the current class.

Code:
$CI->db->query('SOME QUERY');

#3
[eluser]Aniket[/eluser]
Try using this
$CI =& get_instance();
$params=$CI->load->database('databasename',TRUE);
then u can use $param->query();

let me knw if any issues....

#4
[eluser]hal10001[/eluser]
[quote author="hal10001" date="1233746328"]I created my own library class, which works fine, but I just can't get connected to the database to run a query. From a function I try to load in the "database" library, but get the following:

Unable to load the requested class: database

This is the basic code:

Code:
class MyClass {

    function myFunction()
    {
        $CI =& get_instance();
        $CI->load->library( 'database' );

        $query = $this->db->query( 'SOME QUERY GOES HERE' );
        return count( $query->result() );
    }
    
}

How do I do this from a library class, and do I need a model, or can I just run the query like normal when using the database class? Thanks![/quote]

Thank you for your help on this. It was a combination of things that you both mentioned. I ended up with the following:

Code:
class MyClass {

    function myFunction()
    {
        $CI =& get_instance();
        $db = $CI->load->database( 'default', TRUE );

        $query = $db->query( 'SOME QUERY GOES HERE' );
        return count( $query->result() );
    }
    
}


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.