dsbo44836129 2014-01-01 20:53
浏览 84
已采纳

调用未定义的方法pdo :: prepare

I'm writing a registration script for a website and tested the code with the function databaseConnection in the registration.php script, everyting worked but now I replaced the databaseConnection function to a seperate file so I dont have to type the same code again every time.

I took the instance from the database from the databaseConnection.php file and loaded it into the private variable $db_connection in registration.php, now I want to prepare the connection for a sql statement but the script returns error ' Call to undefined method DatabaseConnection::prepare()'

This is the databaseConnection.php script

<?php
class DatabaseConnection {
//private zodat niemand een nieuwe kan maken
private static $instance = null;
//constructor private zodat niemand instantie kan klonen
private function __construct(){
    try{
        $this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
        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;
}
}
?>

I loaded the instance into $db_connection in my __construct function in registration.php like this

$this->db_connection = databaseConnection::getInstance();

Now my code crashes on the $check_user_name=... line

...
        } else if ($this->db_connection != null){
        $check_username_query = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email'); 
...

Can someone help me solve this error? I read the similar questions on stackoverflow but couldn't figure it out with the information given in there.

Regards

  • 写回答

2条回答 默认 最新

  • douquan1953 2014-01-01 20:55
    关注

    Read the error message more carefully: 'Call to undefined method DatabaseConnection::prepare()'

    Your DatabaseConnection::getInstance() returns an instance of DatabaseConnection instead of PDO. One possible solution would be implementing __call() in DatabaseConnection or extending PDO like Chris Barrett said.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化