问题描述:

Please help:

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\ooploginreg\functions.php on line 14 Call Stack # Time Memory Function Location 1 0.0010 252552 {main}( ) ..\register.php:0 2 0.0020 265888 LoginRegistration->registerUser( ) ..\register.php:50

Codeline in functions.php:

<?php

require "config.php";

class LoginRegistration{

function _construct(){

$database = new DatabaseConnection();

}

public function registerUser($username, $password, $name, $email, $website){

global $pdo;

$query = $pdo->prepare("SELECT id FROM users WHERE username = ? AND email = ?");

$query->execute(array($username, $email));

$num = $query->rowCount;

if($num == 0){

$query = $pdo->prepare("INSERT INTO users (username, password, name, email, website)VALUES (?, ?, ?, ? ,?)");

$query->execute(array($username, $password, $name, $email, $website));

return true;

}else{

return print "<span style='color:=#e53d37'>Error...username/email already used.</span>";

}

}

}

?>

网友答案:

It looks like you are calling $pdo before it is initialized.

网友答案:

You called database connection in constructor. But your var "pdo" already have value. Your PDO make some data before this class runs.

Just Use

$this->database = new DatabaseConnection();
网友答案:

You create the variable $database but never used it:

$database = new DatabaseConnection();

Problems

  • You never used the $database variable
  • It is bad practice to use global
  • It is bad practice to have your class depend on database object
  • Connection should be passed to constructor

Solution

Your class should be like this:

class LoginRegistration
{
    private $pdo;
    function __construct($database)
    {
        $this->pdo = $database;
    }

    public function registerUser($username, $password, $name, $email, $website)
    {
        $query = $this->pdo->prepare("SELECT id FROM users WHERE username = ? AND email = ?");
        $query->execute(array($username, $email));
        $num = $query->rowCount;

        if ($num == 0) {
            $query = $this->pdo->prepare("INSERT INTO users (username, password, name, email, website)VALUES (?, ?, ?, ? ,?)");
            $query->execute(array($username, $password, $name, $email, $website));
            return true;
        } else {
            return print "<span style='color:=#e53d37'>Error...username/email already used.</span>";
        }
    }
}

usage:

$database = new DatabaseConnection();
$login = new LoginRegistration($database);
相关阅读:
Top