dousuo8400 2012-07-08 15:55
浏览 60

php error在非对象上调用成员函数query()[关闭]

db_class.php

<?php
class db_mysql
{
    private $dbhost; 
    private $dbusername;
    private $dbpassword;
    private $db;

    //Class is called with all parameters to make a successful connection.
    //
    function __construct($dbhost,$dbusername,$dbpassword,$db)
        {

        global $dbh;
        try {
                $dbh = new PDO("mysql:host=$dbhost;dbname=$db", $dbusername, $dbpassword);
            foreach($dbh->query('show tables;') as $row) {
            print_r($row);
            }
            //$dbh = null;
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }

        }

    //Function to execute a query in the database and return result in a array
    //
    function db_mysql_query($queryst)
    {   
        foreach($dbh->query($queryst) as $row) {
            print_r($row);
            }
    }

}

index.php:

<?php
include 'db_class.php';

$db_m = new db_mysql('localhost','root','','arsaas'); 
$db_m->db_mysql_query('show tables;'); 
?>

Executing index.php gives the following error: Notice: Undefined variable: dbh in C:\xampp\htdocs\srry\db_class.php on line 32

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\srry\db_class.php on line 32

Why does it say dbh is undefined variable when it is instantiated and declared as a global variable in the class constructor?

Any help is appreciated. Thanks in advance.

AR

  • 写回答

1条回答 默认 最新

  • douzi6060 2012-07-08 16:05
    关注

    db_mysql_query method doesn't define variable $dbh, therefore trying to call method query on non-object is not working. You could store PDO object ($dbh) into db_mysql object in the constructor and use it when calling db_mysql_query. If you are trying to use only one database connection then I suggest you to consider using singleton pattern in your db_mysql class. http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题