PHP中未定义的变量

-3 php undefined

我正试图通过使用PDO for MYSQL在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();
}

}
Run Code Online (Sandbox Code Playgroud)

这是我的用户类:

// 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
Run Code Online (Sandbox Code Playgroud)

这是我的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
Run Code Online (Sandbox Code Playgroud)

请告诉我哪里出错了.即使在经过教程后的示例之后做了示例,我显然也不了解面向对象的编码.

我只想创建一个WORKS的注册系统,它采用模块化的OO代码方式.

Jon*_*Jon 5

db在DB类中创建它时,它在本地范围内.您希望它在类范围内(即类变量).更改$db数据库类以$this->db将其放入类范围并通过所有类函数实现.