-3

我正在努力使用面向 MYSQL 的 PDO,在 PHP 中使用 OO 编码生成一个体面的注册、登录和注销。

我收到错误消息:

注意:未定义的变量:第 34 行 D:\xampp\htdocs\dan\classes\DB.class.php 中的 db

致命错误:在第 34 行对 D:\xampp\htdocs\dan\classes\DB.class.php 中的非对象调用成员函数 query()

这是我的数据库类文件..

class DB {

protected $db_name = 'test';
protected $db_user = 'root';
protected $db_pass = '' ;
protected $db_host = 'localhost';

//***************** OPEN connection to database *****************
// Ensure called on every page that needs db connection
public function connect() {
    try {
        // Call PDO class
        $db = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass);
    }
    catch(PDOException $e) {
        // If error, nice error message here
        echo $e->getMessage();
    }
    return true;
}

//******** SELECT rows from database *****************
// Returns a full row or rows from $table using $where as the where clause
// Return value is associative array with column names as keys
public function select($table, $where)
{
    $query = $db->query('SELECT * FROM $table WHERE $where');
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
    $num_rows = $result->rowCount();

    // if only one result, return that single result
    if($num_rows == 1)
        {return $result[0];}
    
    // but if numerous results, return the array
    return $result;
}

//*********** UPDATE a row in database *****************
// Takes array of data, where keys in array are column names
// Value is the data to be inserted into columns
// $table is the name of the table and $where is the SQL WHERE clause
public function update($data, $table, $where) {
    foreach ($data as $column => $value) {
        $sql = "UPDATE $table SET $column = $value WHERE $where";
        try{
            $db->query($sql);
        }
        catch(PDOException $ex){
            echo "error, ".$ex->getMessage();
        }
    }
    return true;
}

//***************** INSERT a new row into database *****************
// Takes array of data, keys in array are column names
// Values are data to be inserted into columns
// $table is the name of table
public function insert($data, $table) {
    $columns = "";
    $values = "";
    
    foreach ($data as $column => $value) {
        $columns .= ($columns == "") ? "" : ", ";
        $columns .= $column;
        $values .= ($values == "") ? "" : ", ";
        $values .= $value;
    }
    
    $sql = "INSERT INTO $table ($columns) VALUES ($values)";
    try{
        $db->query($sql);
    }
    catch(PDOException $ex){
        echo "error, ".$ex->getMessage();
    }

    
    // return the ID of the user in the database
    return $db->lastInsertId();
}

}

这是我的用户类:

// User.class.php
// User object represents a person

require_once 'DB.class.php'; // note: outside of class


class User {
public $id;
public $username;
public $hashedPassword;
public $email;
public $joinDate;

// Constructor is called whenever new object is created
// Takes an associative array with db row as argument, keys are columns in table
function __construct($data) {
    $this->id                   = (isset($data['id']))          ? $data['id']           : "";
    $this->username             = (isset($data['username']))    ? $data['username']     : "";
    $this->hashedPassword   = (isset($data['password']))    ? $data['password'] : "";
    $this->email                = (isset($data['email']))       ? $data['email']        : "";
    $this->joinDate         = (isset($data['joinDate']))    ? $data['joinDate'] : "";
}

public function save($isNewUser = FALSE) {
    // create new db object
    $db = new DB();

    // if the user is already registered, just an update
    if(!$isNewUser) {
        // set the data array
        $data = array(
        "username"  => "'$this->username'",
        "password"  => "'$this->hashedPassword'",
        "email"         => "'$this->email'"
        );
        
        // update the row in database
        $db->update($data, 'users', 'id = ' . $this->id);
    }
    // if user being registered
    else {
        $data = array(
        "username"  => "'$this->username'",
        "password"  => "'$this->hashedPassword'",
        "email"         => "'$this->email'",
        "join_date"  => "'".date("Y-m-d H:i:s",time())."'"
        );
        
        $this->id = $db->insert($data, 'users');
        $this->joinDate = time();
    }
    return true;
}


} // end of class

这是我的 UserTools 类:

// UserTools.class.php

require_once 'User.class.php';
require_once 'DB.class.php';

class UserTools {

// Log in user (REQUIRES DB)
// First checks if username and password match row in db
// If yes, set session vars and store user object within
public function login($username, $password)
{
    $db = new DB();
    $db->connect();

    // need to change to PREPARE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    $hashedPassword = md5($password);
    $result = $db->query("SELECT * FROM users WHERE username = '$username' AND password = '$hashedPassword'");
    
    if($result->rowCount() == 1)
    {
        $_SESSION['user'] = serialize(new User($result));
        $_SESSION['login_time'] = time();
        $_SESSION['logged_in'] = 1;
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

// Log the user out (destroy session vars)
public function logout() {
    unset($_SESSION['user']);
    unset($_SESSION['login_time']);
    unset($_SESSION['logged_in']);
    session_destroy();
}

// Check if username exists (called during registration)  (REQUIRES DB)
public function CheckUsernameExists($username) {
    $db = new DB();
    $db->connect();
    // CHANGE TO PREPARE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    $result = $db->select("users","username=".$username);
            
    if(($result->rowCount()) == 0)
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

// Get a user
// Returns a User object, takes user id as input
public function get($id) {
    // unsure if to delete the following:
    $db = new DB();
    $db->connect();
    $result = $db->select('users', "id = $id");
    return new User($result);
}



} // end of class

请告诉我哪里出错了。我显然不理解面向对象的编码,即使是在一个又一个例子又一个例子又一个例子之后。

我只想创建一个有效的注册系统,并且采用模块化、OO 风格的代码。

4

1 回答 1

5

db当您在 DB 类中创建它时,它在本地范围内。您希望它在类范围内(即类变量)。$db将您的 DB 类更改$this->db为将其放入类范围并通过所有类函数使用它。

于 2013-02-03T21:38:53.860 回答