12-29-2007, 03:45 PM
|
#6 (permalink)
|
|
The Wanderer
Join Date: Dec 2007
Location: 127.0.0.1
Posts: 19
Thanks: 7
|
You're trying to access $this->db. I reckon that you were planning to write your own Database class. Your class is a mix of database access, output and access on user data. A class should not contain any HTML or access on superglobals like $_POST, $_GET, etc. for portability reasons. So it might be better to separate the output from the user interaction and the logic like it's done in MVC structures. SHA1 is more secure than MD5 so you should use sha1() instead of md5(). Here's how I would have realized it:
PHP Code:
class Users { private $db = nulll ; /** * Constructor of the class * * @param Database $db */ public function __construct ( Database $db ) { $this->db = $db ; } /** * Returns the last login of a user * * @param integer $userId * @return integer UNIX timestamp */ public function getLastLogin ( $userId ) { $query = $this->db->query ( 'SELECT last_login FROM `users` WHERE id = ?', $userId ) ; $row = $this->db->fetchRow ( $query, Database::FETCHMODE_NUM ) ; return $row [ 0 ] ; } /** * Checks if the username and the password are correct * * @param string $username * @param string $password * @return boolean */ public function login ( $username , $password ) { $query = $this->db->query ( 'SELECT count(id) FROM user WHERE username = ? AND password = ?', $username, sha1($password) ) ; $row = $this->db->fetchRow ( $query, Database::FETCHMODE_NUM ) ; return $row [ 0 ] > 0 ; } /** * Registers an account * * @param string $username * @param string $password * @param string $eMail * @param integer $userLevel */ public function register ( $username , $password , $eMail , $userLevel ) { $data = array ( 'username' => $username , 'password' => sha1 ( $password ) , 'email' => $eMail , 'user_level' => $userLevel ) ; $this->db->insert ( $data, 'user' ) ; } }
And here's the structure of the Database class. I haven't implemented the methods itself because there are enough resources on the internet about how to create a database class.
PHP Code:
class Database { const FETCHMODE_NUM = 0 ; const FETCHMODE_ASSOC = 1 ; //add more types... /** * Executes a SQL query * * @param string $sql * @param array $bindings */ public function query ($sql, array $bindings = array ( )) { //... } /** * Gets a row * * @param resource $query * @param integer $fetchMode */ public function fetchRow ( $query , $fetchMode = self::FETCHMODE_ASSOC ) { //... } /** * Inserts a row * * @param array $data * @param string $tableName */ public function insert ( array $data , $tableName ) { //... } }
Both class should be self-explanatory.
If you have any questions don't hesitate to ask. Thanks. 
Last edited by deflated : 07-18-2010 at 01:42 PM.
|
|
|
|