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) { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致