Reputation: 535
here is my custom class in library folder in codeigniter
class Commonlib {
public function __construct()
{
$ci=& get_instance();
$ci->load->database();
}
function getcountries(){
return $ci->db->get("countries")->result();
}
function cities(){
return $ci->db->get("cities")->result();
}
}
here is my view
$results=$this->commonlib->getcountries();
foreach ($results as $row)
{
echo '<a href="#">'.$row->country .'</a><br>';
}
error is Severity: Notice Message: Undefined variable: ci how to load database in library construct function
Upvotes: 4
Views: 2959
Reputation: 136
please try to create helper
create helper in dir app/helpers/
layout_helper.php
function getcountries()
{
$CI = & get_instance();
return $CI->db->get("countries")->result();
}
and now that function use is view file like that :
$result = getcountries();
foreach ($results as $row)
{
echo '<a href="#">'.$row->country .'</a><br>';
}
Upvotes: 0
Reputation: 3721
Try the below code. there are some changes suggested
class Commonlib {
private $ci;
public function __construct()
{
$this -> ci=& get_instance();
$this -> ci->load->database();
}
function getcountries(){
return $this -> ci->db->get("countries")->result();
}
function cities(){
return $this -> ci->db->get("cities")->result();
}
}
Note: In your old code $db
in __construct()
method will have scope with in that method only. For get the ci
object globally with in that entire class I used $this
.
Upvotes: 5