【发布时间】:2018-06-01 10:12:10
【问题描述】:
我正在尝试了解如何在课程中使用PDO。我写了这个简单的类,它拥有一个PDO 连接,它作为__construct() 的一部分在另一个类中传递。问题是每次我尝试使用需要数据库连接的类的方法时,我都会收到一条与PDO 的内置函数相关的错误消息,如prepare()、execute()。错误是PHP Fatal error: Uncaught Error: Call to undefined method Database::prepare()。我该如何解决这个问题?我已经阅读了有关依赖注入的内容,但现在在使用 PDO 时如何将这种模式应用于代码有点令人困惑@
<?php
class Database {
public function __construct() {
return $this->db = new PDO("mysql:host=localhost;dbname=testdb;", "root", "root");
}
}
class user {
public function __construct($db) {
$this->db = $db;
}
public function createUser($email, $username, $password) {
$stmt = $this->db->prepare("INSERT INTO users (email,username,password) VALUES (?, ?, ? )");
if ($stmt->execute(array($email, $username, $password))) {
echo "Account successful created";
} else {
echo "Something was wrong during the registration process.";
}
}
public function loginUser($username, $password) {
$stmt = $this->db->prepare("SELECT email,username,password FROM users WHERE email = ? OR username = ?");
$stmt->execute(array($username, $username));
if ($stmt->rowCount() > 0) {
$result = $stmt->fetch(PDO::FETCH_OBJ);
if (password_verify($password, $result->password)) {
echo "logged";
} else {
echo "wrong password";
}
} else {
echo "Username or email does not exist in the database.";
}
}
}
【问题讨论】:
-
修复引号以正确突出显示。
-
修复这一行 return $this->db = new PDO('mysql:host=localhost;dbname=testdb;','root','root');
-
引用已修复,对错字表示抱歉!
-
你是通过
Database的实例向User传递,而不是PDO的实例。在Database中为您的数据库处理程序创建一个getter/setter,例如getConnection(),然后您可以执行$this->db->getConnection()->prepare,或者只是摆脱封装并将PDO的实例传递给User -
@DarkBee 你能举个例子吗?