PHP:Can';t访问函数中的$db变量';s范围


PHP: Can't access $db variable in function's Scope

我创建了一个函数来检查记录是否存在,但它会给我以下错误:

注意:第31行D:''wamp''www''Whq''admin_operation.php中的未定义变量:db

致命错误:在第31行的D:''wamp''www''Whq''admin_operation.php中的非对象上调用成员函数query()

if($mode=='add_image')  
{    $tags_array = array();
     $tags = $_POST['tags'];
    /*function to check tag exist or not */
     function check_tag_exist($t)
     {  
       $result = $db->query('select tag_name from whq_tags where tag_name like "'.$t.'" ');
       $no=$result->num_rows;
       if($no==0)   
       { 
         return true;
       }
       else
       {
         return false;
       }
    }
    /* prepared stmnt created for whq_tags table */
    if($stmt = $db->prepare('insert into whq_tags(tag_name) values (?)'))
    {
       $stmt -> bind_param('s', $tags_name);
       foreach($tags as $tag1)
       {
            $tag1 = $tags_name;
            if(check_tag_exist($tags_name))
            {
              $db->execute();
            }
        }   
       /* Close the statement */
        $stmt->close();
    } 
    else 
    {
      /* Error */
      printf("Prepared Statement Error: %s'n", $db->error);
    }
}

check_tag_exist函数中的变量$db不起作用,而它在其他地方起作用。请帮帮我。提前谢谢。

由于变量作用域的原因,该变量在函数中不可访问。

从PHP文档中读取变量作用域。

您可以将$db变量作为参数传递到函数中:

function check_tag_exist($t, $db) { ... }