extending PDO class
Asked Answered
V

2

14

Below is the db connection class I came out with so far, but I am going to improve it by extending the PDO class itself,

<?php
class database
{
    protected $connection = null;

    #make a connection
    public function __construct($hostname,$dbname,$username,$password)
    {
        try 
        {
            # MySQL with PDO_MYSQL  
            $this->connection = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        }
        catch (PDOException $e) 
        {
            $this->connection = null;
            die($e->getMessage());
        }
    }

    #get the number of rows in a result
    public function num_rows($query)
    {
        # create a prepared statement
        $stmt = $this->connection->prepare($query);

        if($stmt) 
        {
            # execute query 
            $stmt->execute();

            return $stmt->rowCount();
        } 
        else
        {
            return self::get_error();
        }
    }

    #display error
    public function get_error() 
    {
        $this->connection->errorInfo();
    }

    # closes the database connection when object is destroyed.
    public function __destruct()
    {
        $this->connection = null;
    }
}
?>

extended class,

class database extends PDO
{

    #make a connection
    public function __construct($hostname,$dbname,$username,$password)
    {
        parent::__construct($hostname,$dbname,$username,$password);

        try 
        { 
            $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        }
        catch (PDOException $e) 
        {
            die($e->getMessage());
        }
    }

    #get the number of rows in a result
    public function num_rows($query)
    {
        # create a prepared statement
        $stmt = parent::prepare($query);

        if($stmt) 
        {
            # execute query 
            $stmt->execute();

            return $stmt->rowCount();
        } 
        else
        {
            return self::get_error();
        }
    }

    #display error
    public function get_error() 
    {
        $this->connection->errorInfo();
    }

    # closes the database connection when object is destroyed.
    public function __destruct()
    {
        $this->connection = null;
    }
}

This is how I instantiate the class,

# the host used to access DB
define('DB_HOST', 'localhost');

# the username used to access DB
define('DB_USER', 'root');

# the password for the username
define('DB_PASS', 'xxx');

# the name of your databse 
define('DB_NAME', 'db_2011'); 

include 'class_database.php';

$connection = new database(DB_HOST,DB_NAME,DB_USER,DB_PASS);
$sql = "
    SELECT *
    FROM root_contacts_cfm
    ORDER BY cnt_id DESC
    ";

$connection->num_rows($sql);

But I have errors when I call this extended pdo class,

Warning: PDO::__construct() expects parameter 4 to be array, string given in C:\wamp\www\xx\class_database.php on line xx

Fatal error: Call to a member function setAttribute() on a non-object in C:\wamp\www\xx\class_database.php on line xx

I have done some research online, I found this basic structure of extending pdo but I dont understand it...

class myPDO extends PDO
{
   public function __construct($dsn, 
                               $username=null, 
                               $password=null, 
                               $driver_options=null)
   {
      parent::__construct($dsn, $username, $password, $driver_options);
   }

   public function query($query)
   {
      $result = parent::query($query);
      // do other stuff you want to do here, then...
      return($result);
   }
}

What is $dsn variable for? How can I pass my $hostname variable into extended pdo class?

Another questions: How can I make a method for displaying error in the extended pdo class? How can I close the connection in the extended pdo class?

It is so difficult to move from mysqli to pdo!

Thanks.

Visayan answered 3/3, 2011 at 0:50 Comment(3)
Looking at what you have written, you really don't need to extend the PDO class. You are only making it harder than it needs to be.Eckert
is extending pdo a bad thing? I had an independent mysqli class before but I was told better off extending mysqli so I thought it must be the same as pdo??Visayan
You don't need to rewrite the constructor btw.Personable
S
5

$dsn is data source name. It handles your hostname for you. You use it like this:

$dsn = 'mysql:dbname=YOUR_DB_NAME;host=YOUR_HOSTNAME'

With the line $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); You have set exceptions to be raised when errors occur (which I like), so in your extended class you can handle errors in exception handlers. If you had a method called getAssoc in your extended PDO class then it would look like this:

/// Get an associative array of results for the sql.
public function getAssoc($sql, $params=array())
{
   try
   {
      $stmt = $this->prepare($sql);
      $params = is_array($params) ? $params : array($params);
      $stmt->execute($params);

      return $stmt->fetchAll(PDO::FETCH_ASSOC);
   }
   catch (Exception $e)
   {
      // Echo the error or Re-throw it to catch it higher up where you have more
      // information on where it occurred in your program.
      // e.g echo 'Error: ' . $e->getMessage(); 

      throw new Exception(
            __METHOD__ . 'Exception Raised for sql: ' . var_export($sql, true) .
            ' Params: ' . var_export($params, true) .
            ' Error_Info: ' . var_export($this->errorInfo(), true),
            0,
            $e);
   }
}
Sidekick answered 3/3, 2011 at 1:37 Comment(1)
thanks Paul. could you please give me an example code you can handle errors in exception handlers...?Visayan
A
5

I would concentrate on what the class needs to do rather than trying to re write the PDO. I had the same idea because i though it would simplify and stream line the code but it doesn't. You end up spending more time working out how to indirectly interface with the PDO.

Alisealisen answered 10/10, 2012 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.