0
我正在編寫一個註冊腳本,用於檢查用戶名是否已存在。我的數據庫實例從databaseconnection.php
到registration.php
,這是錯誤:調用未定義的方法DatabaseConnection :: prepare()。無法使用bindValue()將值添加到pdo對象
但現在我越來越近了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();
...
謝謝!完全忽略了這個變量。 – Gijs