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

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型