Home » Php » php – Using a database class in my user class

php – Using a database class in my user class

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

Now I need to create a members area on my site, and I was going to build a users class that would handle registration, logging in, password/username changes/resets and logging out. In this users class I need to use MySQL for obvious reasons… which is what my database class was made for.

But I’m confused as to how I would use my database class in my users class. Would I want to create a new database object for my user class and then have it close whenever a method in that class is finished? Or do I somehow make a ‘global’ database class that can be used throughout my entire script (if this is the case I need help with that, no idea what to do there.)

Thanks for any feedback you can give me.

How to&Answers:

Simple, 3 step process.
1/ Create a database object.
2/ Give it to your user class constructor.
3/ Use it in the user methods.

Little example.

File Database.class.php :

<?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 want the current trendy name of this old technique, google “Dependency Injection”. The Singleton pattern in php will fade away soon.

Answer:

As he said, put all your functions in the database class and use the database object to access those functions from your user class. This should be the best method in your case.
Eg:


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

Answer:

What I like to do is make the database class with the Singleton pattern in mind. That way, if you already have a database object, it just retrieves it, otherwise 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 User‘s $_link property to do the database functions, like $this->_link->query(...). You don’t necessarily have to put the Db::getLink() in the constructor if your class doesn’t have to interact with the database that much.

Answer:

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

Answer:

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;
        }
    }
?>

Answer:

I think the better aproach would be to create the database class that instatiate right away on its own on a database.php and then include it on user.php. then every time you create a function that needs a database, you globalise 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 the 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);

}
}

?>