致命错误:未捕获错误:对null调用成员函数query()/prepare()pdo功能不起作用它总是说调用成员函数

rggaifut  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(269)

这是我的班级代码

<?php 

class DatabaseFunctions{

    public $serverName  = SERVER_NAME ;
    public $userName    = USER_NAME ;
    public $password    = PASSWORD ;
    public $dbName      = DB_NAME ;

    public $pdo;
    public $error;

    public function __construct()
    {
        $this->db_connect();        
    }

    private function db_connect()
    {
        try {
            $pdo = new PDO("mysql:host=$this->serverName;dbname=$this->dbName", 
                   $this->userName, $this->password);    
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            //echo 'Connected successfully'; 
            }

        catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    }
    public function userIndex($query)
    {       
        //$stmt = $this->pdo->query($query);
        $stmt = $this->pdo->prepare($query);
        $stmt->execute();

        if($stmt-> rowCount() > 0)
        {
            return $read;
        }
        else
        {
        return false;
        }
    }

}

这是我的

<?php
    session_start();    
    include('../../class/config.php');
    include('../../class/DatabaseFunctions.php');
    if(isset($_SESSION['user'])) {

    $db=new DatabaseFunctions();
    $query='SELECT * FROM members';
    $read=$db->userIndex($query);   
    print_r($read); 
    ?>

致命错误:未捕获错误:在d:\laravel\xamp\u new\htdocs\mou\bikroy\bikroyplus\class\databasefunctions中对null调用成员函数query()。php:33 stack 跟踪:#0 d:\laravel\xamp\u new\htdocs\mou\bikroy\bikroyplus\admin\pages\users.php(12):databasefunctions->userindex('select*from m m...)#1{main}抛出第33行的d:\laravel\xamp\u new\htdocs\mou\bikroy\bikroyplus\class\databasefunctions.php
是错误。。请帮帮我。。注意:数据库已成功连接。但pdo功能不起作用。它表示对成员函数的调用。请帮帮我。

vfhzx4xs

vfhzx4xs1#

在连接函数中, $pdo 仅在函数内部定义,您需要将其分配给 $this->pdo ...

function db_connect() { 
    try { 
        $this->pdo = new PDO("mysql:host=$this->serverName;dbname=$this->dbName", 
            $this->userName, $this->password); 
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

        //echo 'Connected successfully'; 
    } catch(PDOException $e) { 
        echo "Connection failed: " . $e->getMessage(); 
    } 
}

相关问题