php error Call to a member function query() on a non-object [closed]

♀尐吖头ヾ 提交于 2020-01-06 07:55:35

问题


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:


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



来源:https://stackoverflow.com/questions/11384514/php-error-call-to-a-member-function-query-on-a-non-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!