Php Can';t使用PDO,get';ArgumentCountError';

Php Can';t使用PDO,get';ArgumentCountError';,php,sql,database,oop,pdo,Php,Sql,Database,Oop,Pdo,我试图通过使用PDO的检索类从数据库中回显数据。我很难做到这一点。有人能帮我吗 此错误显示: 致命错误:Uncaught ArgumentCounter错误:函数检索的参数太少::#u construct(),在第89行的index.php中传递了0,在index.php中正好需要1。php:58堆栈跟踪:#0 index.php(89):检索->在第58行的index.php中抛出的#u construct()#1{main} 这是我的代码: 上缺少参数 $object = new Retr

我试图通过使用PDO的检索类从数据库中回显数据。我很难做到这一点。有人能帮我吗

此错误显示:

致命错误:Uncaught ArgumentCounter错误:函数检索的参数太少::#u construct(),在第89行的index.php中传递了0,在index.php中正好需要1。php:58堆栈跟踪:#0 index.php(89):检索->在第58行的index.php中抛出的#u construct()#1{main}

这是我的代码:

上缺少参数

$object = new Retrieve;
//Should be $object = new Retrieve($your_db);
你要求就此事进行辩论

public function __construct($db) {
        $this->conn = $db;
    }
既然你已经从父母那里继承了

你为什么不干脆 在您的构造中添加
$this->connect()
而不是

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

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

$object = new Retrieve; // <-- where is the argument?
echo $object->read();
$object=新检索;//read();
您的代码在这一点上令人困惑。如果检索类需要构造函数中的数据库实例,为什么要扩展数据库类

试试这个:

<?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的继承,并传递了正确的构造函数参数进行检索。

我从教程中借用了一些代码,只是添加了自己的代码。您能够修复我遇到的第一个错误(非常感谢),但现在我遇到了另一个错误。我遇到的新错误是:成功连接致命错误:未捕获错误:调用索引中未定义的方法数据库::prepare()。php:39堆栈跟踪:#0 index2.php(50):Retrieve->read()#1{main}在第39行的index.php中抛出,我不确定如何修复这个问题。如果查看数据库类,没有定义“prepare”方法,只有“connect”。看起来你没有从教程中完全导入这个类。这对我来说还是太混乱了。我会尽力解决这个问题,谢谢你的建议,非常有用谢谢你解决了这个问题,但是现在我又遇到了一个错误。它是:成功连接致命错误:未捕获错误:调用index.php中未定义的方法Database::prepare()。php:39堆栈跟踪:#0 index2.php(50):Retrieve->read()#1{main}在index.php行中抛出39@codo7081我已经更新了我的答案,我也尝试过了,但仍然会出错。谢谢你的帮助,我会找到解决办法。@codo7081能给我看看你的班级吗?