Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP and PDO

Tags:

oop

php

My first real foray into using PHP OOP and PDO extensively. I have finally gotten the script to work, but as you notice in order to do it I had to move the PDO connect into the login function - originally it was just in the __construct(). I do not want to have to open a new PDO connect and this is sloppy. How can I maintain the same connection throughout the whole class?

 <?php
class user{

public $id;
public $name;
public $email;
private $password;

public function __construct() {
    $DBH = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");  
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

public function login($email,$password,$type){

    $DBH = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");  
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $password_hash = sha1($password);
    try{
        if ($type != "actives") {
            throw new Exception("Type Handling Error");
        }
        $STH = $DBH->query("SELECT id, email, password FROM $type WHERE email='$email' AND password='$password_hash'");
        $STH->setFetchMode(PDO::FETCH_ASSOC);  
        $row_count = $STH->rowCount();  
        $row = $STH->fetch();

        if($row_count == 1){
            session_start();
            session_regenerate_id();
            $_SESSION['id'] == $row[id];
            return true;
        }
        else{
        return false;
        }
    }
    catch (Exception $e) {
        echo $e->getMessage();
    }

}

public function loggout(){
    session_destroy();
    setcookie(session_name(), session_id(), 1, '/');
}
like image 460
Ryan Hemelt Avatar asked Mar 02 '26 06:03

Ryan Hemelt


2 Answers

Make the database handle a private member within the class:

class user
{    
    public $id;
    public $name;
    public $email;
    private $password;
    private $dbh;

    public function __construct(PDO $dbh)
    {
        $this->dbh = $dbh;  
    }

    public function login($email, $password, $type)
    {
        $dbh = $this->dbh;
        ...
    }

Usage:

$pdo = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user = new User($pdo);
like image 179
ceejayoz Avatar answered Mar 03 '26 22:03

ceejayoz


Sooner or later, you may need the PDO connection object somewhere else in your code(outside your user object). Therefore, I would suggest to use one class which will provide static method as below to get the PDO connection object everywhere you want.

             class Database{
                    private static $datasource='mysql:host=HOST dbname=DB';
                    private static $username='USER';
                    private static $password='PASS';
                    private static $db;

                    //make the constructor private and empty so that no code will create an object of this class.
                    private function __construct(){}

                     //the main public function which will return the required PDO object
                     public static function getDB(){
                      if(!isset(self::$db)){
                           try{
                         self::$db=new PDO(self::$datasoure,self::$username,self::$password);

                            }
                            catch(PDOExceptin $e)
                            {
                               $error=$e->getMessage(); //variable $error can be used in the database_error.php file 
                               //display database error file.
                               include('database_error.php');
                               exit();
                            }
                      }
                        return self::$db; 
                     }

                    }

Then you can use the static method like below any time you want PDO connection

                    $conn=Database::getDB();
like image 45
user1062893 Avatar answered Mar 03 '26 20:03

user1062893



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!