CodeIgniter Forums
Problem with database queries - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Problem with database queries (/showthread.php?tid=8887)



Problem with database queries - El Forum - 06-04-2008

[eluser]Olivier M.[/eluser]
Hi everybody...

I try to make a small application. I have written a small librairy :

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
// MOTEUR DE CALCUL DE DIMECO2

class Dimeco2_lib
{
    var $CI;
    
    function calcul($data)
    {
        $CI =& get_instance();
        $dataprout=$data;
        
        $this->CI->db->select('jour, temperature');
        $query = $this->CI->db->get('biarritz2005_quotidien');
        
                
        $i=0;
        foreach ($query->result_array() as $row)
        {
            $data1[$i]=$row['jour'];
            $data2[$i]=$row['temperature'];
            $i++;
        }    
        
        $dataprout['donnees']=array("data1"=>$data1,"data2"=>$data2);
        return $dataprout;
        
    }
    

    
    
}


?>

But it doesn't work and I don't know why because the same code works in a controller (without CI) :

Code:
<?php



class Test extends Controller{

    function index(){
    
        $this->db->select('jour, temperature');
        $query = $this->db->get('biarritz2005_quotidien');
        
    
        
        
        $i=0;
        foreach ($query->result_array() as $row)
        {
            $data1[$i]=$row['jour'];
            $data2[$i]=$row['temperature'];
            $i++;
        }    
        
        print_r($data2);
    }
}
?>

So my questions :
- someone can help me ???
- why we must use "$this->CI" in a library ?


Problem with database queries - El Forum - 06-04-2008

[eluser]crumpet[/eluser]
$CI =& get_instance();
neeeds to be
$this->CI =& get_instance();


Problem with database queries - El Forum - 06-05-2008

[eluser]Olivier M.[/eluser]
Thanks a lot !!!!

Why we must use this syntax ?


Problem with database queries - El Forum - 06-05-2008

[eluser]Michael Wales[/eluser]
Because you want to assign the class variable to the returned value of get_instance().

Your current code is assigned a method variable to that return value - PHP's scoping only allows this value to be accessible from within the same method (unless passed as a parameter).

The class variable is scoped to be accessible from the entire class.

PHP.net: Variable Scope


Problem with database queries - El Forum - 06-06-2008

[eluser]Olivier M.[/eluser]
Thank you Michael you're a good professor !