Board index   FAQ   Search  
Register  Login
Board index PHP Your Scripts

Connect to PDO Database using OOP

This is where you share YOUR scripts with others

Moderators: macek, egami, gesf

Connect to PDO Database using OOP

Postby Strider64 » Sat Jun 08, 2013 1:44 pm

Here's a simple connection script:

Code: Select all
<?php

/**
 *   PDO database; only one connection is allowed.
 */

class Database {

  private $_pdo;
  // Store the single instance.
  private static $_instance;
 
  /**
   * Get an instance of the Database.
   * @return Database
   */
  public static function getInstance() {
    if (!self::$_instance) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }
 
  /**
   * Constructor
   */
  public function __construct() {
   $db_options = array(
      PDO::ATTR_EMULATE_PREPARES => false                     // important! use actual prepared statements (default: emulate prepared statements)
      , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION           // throw exceptions on errors (default: stay silent)
      , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC      // fetch associative arrays (default: mixed arrays)
   );       
   
   $this->_pdo = new PDO('mysql:host=localhost;dbname=Your_Database;charset=utf8', 'root', 'Your_Password', $db_options);
  }
 
  /**
   * Empty clone magic method to prevent duplication.
   */
  private function __clone() {}
 
  /**
   * Get the PDO connection.
   */
  public function getConnection() {
    return $this->_pdo;
  }
}


Then in your main file, you would call it like such:
Code: Select all
require ('class.database.inc.php');
$db = Database::getInstance();
$pdo = $db->getConnection();
User avatar
Strider64
New php-forum User
New php-forum User
 
Posts: 63
Joined: Sat Mar 23, 2013 8:24 am

Return to Your Scripts

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron