致命错误:在php中调用null上的成员函数prepare()

时间:2017-11-14 04:27:10

标签: php mysqli

尝试连接数据库并获取详细信息,但显示错误:

  

致命错误:在null

上调用成员函数prepare()

我在尝试:

<?php
class Database
{

    private $host = "******";
    private $db_name = "******";
    private $username = "******";
    private $password = "******";
    public $conn;

    public function dbConnection()
    {

        $this->conn = null;    
        try
        {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

prepare代码在 class.user.php 中定义:

<?php
require_once 'lang.php';
require_once 'dbconfig.php';
class USER
{   
    private $conn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }
//More codes...
}
?>

1 个答案:

答案 0 :(得分:0)

由于连接MySQL数据库而导致错误,该数据库不允许外部访问!

对不起commentors因为麻烦你。

相关问题