Board index   FAQ   Search  
Register  Login
Board index PHP PHP Scripts

1 database for multiple php scripts?

Links for php scripts

Moderators: macek, egami, gesf

1 database for multiple php scripts?

Postby whitalockz » Thu Apr 11, 2013 12:03 pm

How do you use 1 database for multiple php scripts? Ok, so i have a lot of different php scripts like user management, shopping cart, forums. I don't want my customers to have to sign-up multiple times for my website. I need to know how to do this.
New php-forum User
New php-forum User
Posts: 1
Joined: Sun Mar 24, 2013 12:54 am

Re: 1 database for multiple php scripts?

Postby 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)) {
    } else {
'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;

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


 * Database class only one connection is allowed.

class Database extends PDO{

    private static 

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

     * empty clone magic method to prevent duplication

private function __clone() {


then it's used as simple as calling
Code: Select all

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.
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Return to PHP 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.