Return to Snippet

Revision: 445
at July 13, 2006 11:47 by Aeon


Initial Code
$local = false;
$master = false;
$host = array('local'=>'localhost','master'=>'192.168.1.1');
function db_conn($type)
{
        global $local,$master,$host;
//      echo 'in db_conn';
        if(${$type} && ${$type}->ping())
        {
//              echo 'connection already exists and is alive';
                return ${$type};
        }
        else
        {
//              echo 'connection does not exist, attempting to connect';
                ${$type} = new mysqli($host[$type],'user','password','database');
                if(${$type})
                {
                        return ${$type};
                }
                else
                {
                        err('Could not connect to '.${$type}.' database.'.mysqli_connect_error());
                        return false;
                }
        }
}

Initial URL


Initial Description
usage is simple:
$result = mysqli_query($query,db_conn('local')); for instance.
if written in patterns, this should probably be a singleton, but I haven't bothered converting it - feel free to comment with your modification though!

Initial Title
mysql connection that re-connects if it's been disconnected

Initial Tags
mysql, php

Initial Language
PHP