register.php

时间:2015-08-11 16:15:45

标签: php function registration

请帮助:  致命错误:在第14行的C:\ wamp \ www \ ooploginreg \ functions.php中调用非对象的成员函数prepare()调用堆栈#时间内存函数位置1 0.0010 252552 {main}().. \ register.php:0 2 0.0020 265888 LoginRegistration-> registerUser().. \ register.php:50

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>";
    }
}
}

?>

3 个答案:

答案 0 :(得分:0)

看起来你在初始化之前调用了$ pdo。

答案 1 :(得分:0)

您在构造函数中调用了数据库连接。但你的var&#34; pdo&#34;已经有了价值。您的PDO在此类运行之前会生成一些数据。

只需使用

$this->database = new DatabaseConnection();

答案 2 :(得分:0)

您创建变量$database但从未使用它:

$database = new DatabaseConnection();

<强>问题

  • 您从未使用$ database变量
  • 使用全球
  • 是不好的做法
  • 让您的类依赖于数据库对象
  • 是不好的做法
  • 应将连接传递给构造函数

<强>解决方案

你的课应该是这样的:

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>";
        }
    }
}

用法:

$database = new DatabaseConnection();
$login = new LoginRegistration($database);