2013-02-03 95 views
-3

我正在試圖用OO編碼在PHP中使用PDO爲MYSQL生成體面的註冊,登錄和註銷。PHP中的未定義變量

我收到錯誤:

Notice: Undefined variable: db in D:\xampp\htdocs\dan\classes\DB.class.php on line 34

Fatal error: Call to a member function query() on a non-object in D:\xampp\htdocs\dan\classes\DB.class.php on line 34

這裏是我的數據庫類文件..

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風格的代碼。

+0

對我的回答最後的評論有幫助嗎?只是想確保你的問題得到解決,所以我可以停止檢查回來,因爲SO沒有通知我回應。 ^^ – Jon

回答

5

db當您在數據庫類中創建它時,它位於本地範圍內。你希望它在類範圍內(即一個類變量)。將您的數據庫類中的$db更改爲$this->db,將其放入類作用域並通過所有類功能進行處理。

+0

我改變了連接()函數中的$ db到$ this-db ... 我將其他成員中的$ db調用更改爲$ this-> db ,,,, 現在出現錯誤... 致命錯誤:調用第35行的D:\ xampp \ htdocs \ dan \ classes \ DB.class.php中的非對象的成員函數fetchAll() –

+0

這是因爲,使用PDO時,需要「準備聲明然後執行它。 - > http://www.php.net/manual/en/pdostatement.execute.php – Jon

+0

我正在閱讀關於PDO的許多衝突的事情。準備,不準備..我正在嘗試遵循一些教程,但它並沒有發生,我發現PHP PDO文檔很難閱讀,我覺得我會放棄。謝謝你的詳細回覆,我感謝它的方式 –