2014-10-19 39 views
0

我創建了一個功能來檢查記錄存在與否,但它給了我這些錯誤:

注意:未定義的變量:DB在d: \ wamp \ www \ Whq \ admin_operation.php on line 31

致命錯誤:調用第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); 
    } 
} 

變量$ db裏面check_tag_exist函數不工作,而它在其他地方工作。請幫助我。 在此先感謝。

+0

$ DB變量在該函數範圍。 – 2014-10-19 06:47:12

+0

您在可見度方面存在問題。在函數外部定義的變量在函數內部是不可見的,除非您將它們作爲參數傳遞或將其聲明爲全局變量。 – 2014-10-19 06:48:07

+1

這是一個可變範圍問題 - http://php.net/manual/en/language.variables.scope.php。添加'$ db'到函數params - >'function check_tag_exist($ t,$ db)' – Sean 2014-10-19 06:48:20

回答

2

由於變量的作用域,變量在您的函數中無法訪問。從PHP文檔閱讀variable scope

可以傳遞$ DB變量到函數作爲參數:

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