无法使用PDO回显数据库类中的行,获取“ ArgumentCountError”

时间:2018-09-25 03:42:14

标签: php sql database oop pdo

我正在尝试使用PDO通过我的检索类从数据库中回显数据。我这样做很麻烦。有人可以帮我吗?

此错误显示:

  

严重错误:未捕获ArgumentCountError:函数检索参数太少:: __ construct(),第89行的index.php中传递了0,而index.php:58中恰好期望了1堆栈跟踪:#0 index.php(89 ):检索-> __ construct()#1 {main}抛出58行中的index.php

这是我的代码:

<?php 
class Database {
	private $host = 'localhost';
	private $db_name = 'photos';
	private $username = 'root';
	private $password = '';
	private $conn;

	public 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 Retrieve extends Database {
	
	private $conn;
	private $table = 'indeximg';

	public $id;
	public $username;
	public $img;

	public function __construct($db) {
		$this->conn = $db;
	}

	public function read() {
		$query = 'SELECT id, username, img FROM' . $this->table;
		$stmt = $this->conn->prepare($query);
		$stmt->execute();
		return $stmt;
	}

}


$object = new Retrieve;
echo $object->read();
?>

2 个答案:

答案 0 :(得分:1)

从您的代码中,Retrieve的构造函数期望一个参数:$db,并且在此处创建实例时您没有传递任何参数:

$object = new Retrieve; // <-- where is the argument?
echo $object->read();

此时,您的代码令人困惑。如果Retrieve类在构造函数中需要Database的实例,为什么要扩展Database类?

尝试一下:

<?php 
class Database {
    private $host = 'localhost';
    private $db_name = 'photos';
    private $username = 'root';
    private $password = '';
    private $conn;

    public 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 Retrieve {

    private $conn;
    private $table = 'indeximg';

    public $id;
    public $username;
    public $img;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function read() {
        $query = 'SELECT id, username, img FROM' . $this->table;
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }

}


$db = new Database();
$db->connect();
$object = new Retrieve($db);
echo $object->read();
?>

我删除了Retrieve的继承并将正确的构造函数参数传递给Retrieve。

答案 1 :(得分:0)

缺少参数。

$object = new Retrieve;
//Should be $object = new Retrieve($your_db);

您已要求争论

public function __construct($db) {
        $this->conn = $db;
    }

而且由于您已经从父级那里继承了

为什么不只是 在您的__construct中添加$this->connect() 代替

$db = new Database();
$db->connect();
$object = new Retrieve($d);
echo $object->read();