doulianxing4015 2014-10-19 06:40
浏览 49
已采纳

PHP:无法在函数的Scope中访问$ db变量[关闭]

I've created a function to check if a record exists or not, but it gives me these errors:

Notice: Undefined variable: db in D:\wamp\www\Whq\admin_operation.php on line 31

Fatal error: Call to a member function query() on a non-object in D:\wamp\www\Whq\admin_operation.php on line 31

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
", $db->error);
    }
}

Variable $db inside check_tag_exist function is not working , while it working at other places. Please help me out. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doujuncuo9339 2014-10-19 06:49
    关注

    that variable isn't accessible in your function, due to variable scope.

    read on variable scope from the PHP docs.

    you can pass the $db variable into the function as a parameter:

    function check_tag_exist($t, $db) { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应