1 database for multiple php scripts?

Links for php scripts

Moderators: macek, egami, gesf

Post Reply
seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

Re: 1 database for multiple php scripts?

Post by seandisanti » Fri Apr 12, 2013 3:35 pm

Use PDO and a Database class that is auto included with a singleton pattern. It's way less complex than it sounds. here's an autoloader script you would put into a functions.php or other file that is loaded with every single page:

Code: Select all


function __autoload($name) {
    $root = getRoot();
    $theClass = $root . 'classes/' . $name . '.php';
    if (file_exists($theClass)) {
        include($theClass);
    } else {
        die('Tried to load non-existent class: ' . $theClass);
    }
}
 
getRoot() there is another function I use to locate the root directory to make all paths absolute without having to use url's. it is:

Code: Select all


function getRoot($uri = '') {
    if ($uri == '') {
        $uri = $_SERVER['PHP_SELF'];
    }
    $depth = substr_count($uri, '/')-1;
    $root = '';
    for ($x = 1; $x <= $depth; $x++)
        $root = '../' . $root;
    return $root;
}
 
That is written on the assumption that the file containing it is one folder off of the root. modify the $depth assignment to increase the decrement by one for every sub folder deeper that you place your file. And the Database.php class extending PDO functionality is very simple.

Code: Select all

<?php

/*
 * Database class only one connection is allowed.
 */

class Database extends PDO{

    private $connection;
    private static $instance;

    public static function getInstance() {
        if (!self::$instance) {
            
            self::$instance = new self("mysql:host=". DBHOST . ";dbname=". DB ,DBUSER,DBPASS);
        }
        return self::$instance;
    }



    /*
     * empty clone magic method to prevent duplication
     *
     */

    private function __clone() {

    }
}
 
then it's used as simple as calling

Code: Select all

$db = Database::getInstance();
 
when you need a database connection. (oh yeah, for this implementation, the login details are included in a constants.php that is included by the functions.php that has the autoloader and getRoot()
I've demonstrated use of these concepts in several posts on this forum, so I'll leave it as an exercise for you to find one of them if you need to see an example of the code working before you implement it.

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests