【发布时间】:2023-03-26 20:35:01
【问题描述】:
我正在尝试为我正在从事的一个项目创建一种面向对象的方法,但我很难理解数据库类的想法。我收到以下错误。
Call to undefined method Database::prepare()
数据库类
class Database
{
protected $connection;
function __construct()
{
$this->createConnection();
}
private function createConnection()
{
$this->connection = new mysqli("localhost", "user", "password", "test");
if ($this->connection->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->connection->connect_errno . ") " . $this->connection->connect_error;
}
else
{
echo 'Connected to database.<br />';
}
}
}
$db = new Database();
用户操作类
class userActions
{
protected $_db;
protected $_username;
protected $_password;
protected $_auth;
protected $tableName;
function __construct($db, $username, $password, $auth)
{
$this->_db = $db;
$this->_username = $username;
$this->_password = $password;
$this->_auth = $auth;
$this->checkUserExists();
}
private function checkUserExists()
{
$query= "SELECT COUNT(*) FROM '{$this->tableName}' WHERE username = ?";
$stmt = $this->_db->prepare($query);
$stmt->bind_param('s', $this->username);
$userNumber= $stmt->execute();
echo $userNumber;
}
}
我做错了什么,我可以做些什么来改进我完成这项任务的方式吗?
【问题讨论】:
-
您的数据库类没有准备例程,不确定您还期望什么......
-
@crowder php.net/manual/en/mysqli.prepare.php
-
但是您(我假设)在这里传递了您的数据库类(如果没有,您为什么要共享该代码)?
-
您似乎希望您的课程能够扩展
mysqli课程。但它只是将mysqli对象存储为私有变量。
标签: php oop mysqli prepared-statement