doudou0111 2014-01-28 11:53 采纳率: 0%
浏览 67
已采纳

在pdo中的非对象上调用成员函数query()

I require the pdo_connect in the index before requiring anything else Using the foreach(see below) in the index.php works but when I use it in the function 'test' (which is a seperate file) I get the error:

Call to a member function query() on a non-object

Already tried requireing the pdo_connect in the seperate file as well which gives the same error

I'm completely new to PDO and a beginner coder and would really appreciate it if someone can help me out!

pdo_connect.php:

        $host= 'localhost';
        $dbname= 'secret';
        $user= 'secret';
        $pass= 'secret';
        $input = 'secret';

        try 
        {  
          $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);  
          $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        }  
        catch(PDOException $e) 
        {
            file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);  
        } 

Function (testfile.php):

function test($UserName,$PassWord)
{

    foreach($DBH->query('SELECT * FROM users') as $row) 
    {
        echo $row['username'].' '.$row['password']; //etc...
    }
}
  • 写回答

1条回答 默认 最新

  • du22399 2014-01-28 11:59
    关注

    You have to pass your $DBH as param to test function, $DBH is not visible inside your test function.

    Try:

    function test($DBH,$UserName,$PassWord)
    {
    
        foreach($DBH->query('SELECT * FROM users') as $row) 
        {
            echo $row['username'].' '.$row['password']; //etc...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?