问题描述:

 if(!empty($home) && !empty($title) && !empty($meta))

{

function updcfg($condition,$status){

$db->query("UPDATE site_config SET status = '".$status."' WHERE condition = '".$condition."' ");

}

updcfg("home",$home);

updcfg("title",$title);

updcfg("meta",$meta);

updcfg("news",$news);

}

the current code that you see above is not working and giving me this error :

Fatal error: Call to a member function query() on a non-object in /home/main.php on line 20

I deleted the function.. and the code worked with no problems ! can anyone tell what is wrong with the code?

网友答案:

pass $db in the function.

function updcfg($condition,$status,$db){
$db->query("UPDATE site_config SET status = '".$status."' WHERE condition = '".$condition."' ");
}
updcfg("home",$home,$db);
网友答案:

You should put the function outside of the if statement.

网友答案:

$db is not defined inside the updcfg function, and is not defined as global. So, there are three oprions: 1. use global keyword:

function updcfg($condition,$status){
global $db;

2. pass $db to the function arguments : function updcfg($condition, $status, $db) 3. init $db inside the function (the way you do it)

网友答案:

please load database class before calling query method

function updcfg($condition,$status){
$this->load->database();
$this->db->query("UPDATE site_config SET status = '".$status."' WHERE condition = '".$condition."' ");
}
网友答案:

You need to initialize the $db variable. If you have initialized before is not alive inside the updcfg function, but you can pass the $db context as parameter:

function updcfg($condition, $status, $db){
    $db->query("UPDATE site_config SET status = '".$status."' WHERE condition = '".$condition."' ");
}
$db = new ....
#Now you can do this
updcfg("home",$home, $db);
updcfg("title",$title,$db);
updcfg("meta",$meta,$db);
updcfg("news",$news,$db);
相关阅读:
Top