尝试使用PDO OOP类回显数据库时,出现“ null的query()”错误?

时间:2018-09-25 20:09:02

标签: php pdo

此代码出现另一个错误。是:

  

连接成功   致命错误:未捕获错误:在index5.php:29中对null调用成员函数query()堆栈跟踪:#0 index5.php(44):User-> getAllUsers()#1 index5.php(55):ViewUser -> showAllUsers()#2 {main}在第29行的index5.php中抛出

我正在尝试从名为“ indeximg”的数据库表中回显数据,但是此代码给了我上面的错误。我不确定如何解决此问题。这是我的代码:

<?php 
class Database {

	private $host = 'localhost';
	private $db_name = 'photos';
	private $username = 'root';
	private $password = '';
	private $conn;

	protected function connect() {	

		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);
			echo "Connected successfully"; 
		} catch(PDOException $e) {
			echo 'Connection Error: ' . $e->getMessage();
		}

		$this->conn = null;
	}

}

class User extends Database {
	
	protected function getAllUsers() {
		$sql = "SELECT * FROM indeximg";
		$result = $this->connect()->query($sql);
		$numRows = $result->num_rows;
		if ($numRows > 0) {
			while ($row = $result->fetch_assoc()) {
				$data[] = $row;
			}
			return $data;
		}
	}

}

class ViewUser extends User {
	
	public function showAllUsers() {
		$datas = $this->getAllUsers();
		foreach ($datas as $data) {
			echo $data['id']."<br>";
			echo $data['username']."<br>";
		}
	}

}


$users = new ViewUser();
$users->showAllUsers();

?>

2 个答案:

答案 0 :(得分:1)

query()方法从null调用,因为您没有从connect()函数返回任何内容。添加一行,如注释中所示。

protected function connect() {  

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);
    echo "Connected successfully"; 
    return $this->conn;//Add this line
} catch(PDOException $e) {
    echo 'Connection Error: ' . $e->getMessage();
}

$this->conn = null;
}

答案 1 :(得分:0)

您的connect()函数中有几个问题:

首先,您将$this->conn设置为null,即使连接成功也是如此。

第二,您将一个函数链接到connect()函数的结果,该函数不返回任何内容:

protected function connect() 
{   
    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);
        echo "Connected successfully";
    } catch(PDOException $e) {
        die('Connection Error: ' . $e->getMessage()); // Or do something else to handle the error
    }

    return $this->conn; 
}