我正在编写一个注册脚本来检查用户名是否已经存在。首先,我无法从databaseconnection.php
to获取我的数据库实例registration.php
,这是错误:调用未定义的方法 DatabaseConnection::prepare()。
但是现在我已经越界了prepare()
,想用 将我的值提供给查询bindValue()
,但是下一个错误是我得到的“调用非对象上的成员函数 bindValue() ”。
这是否仍然意味着我没有得到正确的数据库实例,而是一个databaseconnection.php
类的实例?
这是databaseconnection.php
<?php
class DatabaseConnection {
private static $instance = null;
public $db_connection;
private function __construct(){
try{
$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
$this->db_connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return true;
} catch (PDOException $exception){
$this->errors[] = $this->lang['Database error'];
return false;
}
}
public static function getInstance(){
if(self::$instance === null){
self::$instance = new DatabaseConnection();
}
return self::$instance;
}
public function __call($method, $args) {
$callable = array($this->pdo, $method);
//is_callable, verify that the contents of a variable can be called as a function
if(is_callable($callable)) {
return call_user_func_array($callable, $args);
}
}
}
?>
在registration.php
我使用此代码将实例放入我的本地私有变量中:
class Registration
{
private $db_connection = null;
public function __construct()
{
$this->db_connection = databaseConnection::getInstance();
...
}
...
}
并希望能够在以下位置执行此查询registration.php
:
...
$check_username_query = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$check_username_query->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$check_username_query->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$check_username_query->execute();
$results = $check_username_query->fetchAll();
...