Question

I'm writing a registration script that checks if the username already exists. First I had troubles getting my database instance from databaseconnection.php to registration.php, this was the error: Call to undefined method DatabaseConnection::prepare().

But now I'm getting past the prepare() line and want to give my values to the query with bindValue(), but this next error is what I get 'Call to a member function bindValue() on a non-object'.

Does this still means I didn't get the correct database instance but a instance of the databaseconnection.php class?

This is 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);
       }
   }
}

?>

In registration.php I use this code to get the instance into my local private variable:

class Registration

{
    private $db_connection = null;


        public function __construct()
    {
        $this->db_connection = databaseConnection::getInstance();
                ...
    }
...
}

And would like to be able to execute this query in 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();
...
Was it helpful?

Solution

$callable = array($this->pdo, $method);

You have instance of PDO in $this->db_connection not $this->pdo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top