Using a database class in my user class

In my project, I have a database class that I use to process all the MySQL stuff. It connects to the database, starts queries, catches errors and closes the connection.

Now I need to create a member area on my site, and I'm going to create a user class that will handle registration, login, password / username / reset, and logout changes. In this user class, I need to use MySQL for obvious reasons ... for which my database class was created.

But I am confused about how I will use my database class in my user class. Should I create a new database object for my custom class and then close it whenever the method in this class is completed? Or am I somehow creating a “global” database class that can be used throughout my script (if so, I need help with this, I don’t know what to do there.)

Thanks for any feedback you can give me.

+7
object database php class
source share
6 answers

A simple, three-step process. 1 / Create a database object. 2 / Give it to the custom class constructor. 3 / Use it in custom methods.

A small example.

Database.class.php file:

<?php class Database{ public function __construct(){ // Connects to database for example. } public function query($sqlQuery){ // Send a query to the database } [...] } 

In User.class.php:

 <?php class User{ private $_db; public function __construct(Database $db){ $this->_db = $db; } public function deleteUser(){ $this->_db->query('DELETE FROM Users WHERE name = "Bobby"'); } } 

Now, in userManager.php, for example:

 <?php $db = new Database(); $user = new User($db); // Say bye to Bobby : $user->deleteUser(); 

If you need the current fashion name of this old technique, google "Injection Dependency". Singleton pattern in php will disappear soon.

+21
source share

According to him, put all your functions in a database class and use the database object to access these functions from your user class. This should be the best method in your case. For example:

global $database;
userclassvar = $database->doSomething();

+1
source share

I like to make a database class with a Singleton pattern . Thus, if you already have a database object, it just retrieves it, otherwise it creates a new one. For example:

 Database.class.php class Db { protected static $_link; private function __construct() { // access your database here, establish link } public static function getLink() { if(self::_link === null) { new Db(); } return self::_link; } // etc. } User.class.php class User { protected $_link; // This will be the database object ... public function __construct() { $this->_link = Db::getLink(); } } 

And now you can use the User $_link to execute database functions, for example $this->_link->query(...) . You do not need to embed Db::getLink() in the constructor if your class does not have to interact much with the database.

+1
source share

Since you are using the database as an object, why not just add methods to the object that your “user class” can use to take care of the things that it needs to do. The users class may contain a pointer to a database class. The database class will protect your database and ensure that the user class uses it appropriately.

0
source share

I think the best aproach would be to create a database class that will immediately install itself on database.php and then enable it on user.php. then every time you create a function that needs a database, you globalize the database object.

Check this. databse.php

 <?php require_once ('includes/config.php'); class MysqlDb{ public $connection; private $last_query; private $magic_quotes_active; private $real_escape_string_exists; public function __construct() { $this->open_connection(); $this->magic_quotes_active = get_magic_quotes_gpc(); $this->real_escape_string_exists = function_exists( "mysql_real_escape_string" ); } public function open_connection() { $this->connection = mysql_connect(DBHOST,DBUSER,DBPASS); if(!$this->connection){ die("Could not Connect ".mysql_error()); }else{ $db = mysql_select_db(DB, $this->connection); } } public function close_connection(){ if(isset($this->connection)){ mysql_close($this->connection); unset($this->connection); } } public function query($sql){ $this->last_query = $sql; $results = mysql_query($sql, $this->connection); $this->comfirm_query($results); return $results; } private function comfirm_query($results){ if(!$results){ $output = "Query Failed " .mysql_error()."<br />"; $output .= "Last Query: " . $this->last_query; die($output); } } public function escape_value($value){ if( $this->real_escape_string_exists ) { if($this->magic_quotes_active ) { $value = stripslashes( $value ); } $value = mysql_real_escape_string( $value ); } else { if( !$this->magic_quotes_active ) { $value = addslashes( $value ); } } return $value; } public function fetch_array($results){ return mysql_fetch_array($results); } public function num_row($results){ return mysql_num_rows($results); } public function insert_id(){ return mysql_insert_id($this->connection); } public function affected_row(){ return mysql_affected_rows(); } } $database = new MysqlDb(); ?> 

here is user.php

 <?php require_once ('includes/database.php'); class User { public $id; public $fName; public $lName; Public $userName; public $password; public $email; public $acess; public static function find_all(){ global $database; return self::find_by_sql("SELECT * FROM users"); } public static function find_by_id($id=0){ global $database; $results_array = self::find_by_sql("SELECT * FROM users where id={$id}"); return !empty($results_array)? array_shift($results_array) : false; } public static function find_by_sql($sql){ global $database; $results = $database -> query($sql); $object_array = array(); while($row = $database -> fetch_array($results)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function instantiate($row){ $user = new self; foreach($row as $attribute => $value){ if($user -> has_attribute($attribute)){ $user -> $attribute = $value; } } return $user; } private function has_attribute($attribute){ $object_vars = get_object_vars($this); return array_key_exists($attribute, $object_vars); } } ?> 
0
source share

Here is a solution using PDO.

 <?php class Database { private static $dbh; public static function connect() { $host = "mysql:dbname=YOUR_DB_NAME;host=YOUR_DB_SERVER"; $username = "YOUR_USERNAME"; $password = "YOUR_PASSWORD"; try { self::$dbh = new PDO( $host, $username, $password ); self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT ); self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch( PDOException $e ){ $error_message = $e->getMessage(); exit(); } return self::$dbh; } } class MYObject { public static $dbh = null; public function __construct(PDO $db = null) { if($db === null){ $this->dbh = Database::connect(); } else { $this->dbh = $db; } } } class User extends myObject { public function __construct($id = null, PDO $db = null) { if($db === null){ parent::__construct(); } else { parent::__construct($db); } if($id !== null){ return $this->select($id); } } public function select($id) { $retVal =false; try { $stmt = $this->dbh->prepare("SELECT..."); $stmt->execute(); if( $stmt->rowCount()==1 ){ $row = $stmt->fetchAll(PDO::FETCH_ASSOC); $retVal =json_encode($row); } } catch (PDOException $e ) { $error_message = $e->getMessage(); exit(); } return $retVal; } } ?> 
0
source share

All Articles