WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : PHP5 Database Objects Using Singleton Pattern
Categories : PHP, PHP Classes Click here to Update Your Picture
Joseph Crawford
Date : Sep 01st 2004
Grade : 2 of 5 (graded 2 times)
Viewed : 8700
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Joseph Crawford
Action : Grade This Code Example
Tools : My Examples List

 
Like this code?
Show the author your appreciation.
Submit your own code examples 
 

this code is by far complete, it contains a few functions to help you on your way. This shows a good example of how Sqlite is used.
I have also shown how to extend classes (Database class is extended to both Sqlite and Myql classes although they could be stand alone) If you know PHP5 well please comment with any suggestions you come up with on how to make this code better.

index.php
<?php
// the following code will make it so that the class directory is in your include_path
// this allows the __autoload function to work.
$cur = ini_get("include_path");
$cur .= PATH_SEPARATOR.dirname(__FILE__).'\\include\\class\\';;
ini_set("include_path", $cur);

// this will load any classes that are not found and are located in the
// /include/class/ folder.

function __autoload($class) {
    include(
$class . '.php');

   
/* Check to see it the include defined the class */
   
if ( !class_exists($class, false) ) {
       
trigger_error("Unable to load class $class", E_USER_ERROR);
    }
}


// get an instance of the sqlite database
$db = Sqlite::getInstance('mysqlitedb', 0666);
$db->Open();
$db->Create();
$result = $db->Query('SELECT * FROM states');
$arr = $db->FetchAll($result);

echo
'<pre>';
print_r($arr);
echo
'</pre>';

/*
// this is how you would use the Mysql class

$db1 = Mysql::getInstance('localhost', 'mydb', 'user', 'password');
$db1->Open();
$result = $db1->Query("SELECT * FROM table");
$arr1 = $db1->FetchArray($result);

echo '<pre>';
print_r($arr1);
echo '</pre>';

*/

?>



/include/class/Database.php
<?
class Database {
   
// an array of properties used by __get and __set
   
private $props;
   
   
// the actual connection resource
   
protected $connection;
   
   
// the hostname for the database server
   
protected $hostname;
   
   
// the name of the database to use
   
protected $database;
   
   
// the username to use to access the database
   
protected $username;
   
   
// the password to use to access the database
   
protected $password;
   
    private function
__construct($dbHost=null, $dbName=null, $dbUser=null, $dbPass=null) {
       
$this->database = $dbName;
       
$this->hostname = $dbHost;
       
$this->username = $dbUser;
       
$this->password = $dbPass;
    }
   
    protected function
__set($name, $value) {
        if (isset(
$this->props[$name])) {
           
$this->props[$name] = $value;
        }
    }
   
    protected function
__get($name) {
        if (isset(
$this->props[$name])) {
            return
$this->props[$name];
        } else {
            return
nulll;   
        }
    }
}
?>



/include/class/Mysql.php
<?

class Mysql extends Database {

    static private
$instance;

    public function
__construct($dbHost=null, $dbName=null, $dbUser=null, $dbPass=null) {
       
parent::__construct($dbHost, $dbName, $dbUser, $dbPass);
    }

    static function
getInstance($dbHost, $dbName, $dbUser, $dbPass) {
        if(!
Mysql::$instance) {
           
Mysql::$instance = new Mysql($dbHost, $dbName, $dbUser, $dbPass);
        }
        return
Mysql::$instance;
    }

    public function
__set($name, $value) {
        if (isset(
$name) && isset($value)) {
           
parent::__set($name, $value);
        }
    }

    public function
__get($name) {
        if (isset(
$name)) {
            return
parent::__get($name);
        }
    }

    public function
Connected() {
        if (
is_resource($this->connection)) {
            return
true;
        } else {
            return
false;
        }
    }

    public function
AffectedRows() {
        return
mysql_affected_rows($this->connection);
    }

    public function
Open() {
        if (
is_null($this->database))
            die(
"MySQL database not selected");
        if (
is_null($this->hostname))
            die(
"MySQL hostname not set");

       
$this->connection = @mysql_connect($this->hostname, $this->username, $this->password);

        if (
$this->connection === false)
        die(
"Could not connect to database. Check your username and password then try again.\n");

        if (!
mysql_select_db($this->database, $this->connection)) {
            die(
"Could not select database");
        }
    }

    public function
Close() {
       
mysql_close($this->connection);
       
$this->connection = null;
    }

    public function
Query($sql) {
        if (
$this->connection === false) {
            die(
'No Database Connection Found.');
        }

       
$result = @mysql_query($sql,$this->connection);
        if (
$result === false) {
            die(
mysql_error());
        }
        return
$result;
    }

    public function
FetchArray($result) {
        if (
$this->connection === false) {
            die(
'No Database Connection Found.');
        }
       
       
$data = @mysql_fetch_array($result);
        if (!
is_array($data)) {
            die(
mysql_error());
        }
        return
$data;
    }
}
?>



/include/class/Sqlite.php
<?

class Sqlite extends Database {

static private
$instance;

private
$error;
private
$permission;

private function
__construct($dbName, $dbPerms) {
 
$this->database = $dbName;
 
$this->permission = $dbPerms;
}

static function
getInstance($dbName=null, $dbPerms=null) {
  if(!
Sqlite::$instance) {
   
Sqlite::$instance = new Sqlite($dbName, $dbPerms);
  }
  return
Sqlite::$instance;
}

public function
Open() {
  if(
is_null($this->database)) {
   die(
"Sqlite database not selected");
  }
  if (
is_null($this->permission)) {
   die(
"Sqlite permissions not set");
  }
  if(
file_exists($this->database)) {
   
$this->connection = sqlite_open($this->database, $this->permission, $this->error);
  } else {
   
$this->connection = sqlite_open($this->database, $this->permission, $this->error);
   
$this->Query('CREATE TABLE states (state varchar(50))');
   
$this->Query("INSERT INTO states VALUES ('vermont')");
   
$this->Query("INSERT INTO states VALUES ('texas')");
  }

  if (
$this->connection === false) {
   die(
$this->error);
  }
}

public function
Close() {
 
sqlite_close($this->connection);
 
$this->connection = null;
}

public function
Query($sql) {
  if (
$this->connection === false) {
   die(
'No Database Connection Found.');
  }
 
$result = sqlite_query($this->connection, $sql);
  if (
$result === false) {
   die(
$sql);
  }
  return
$result;
}

public function
FetchArray($result) {
  if (
$this->connection === false) {
   die(
'No Database Connection Found.');
  }

 
$data = @sqlite_fetch_array($result);
  if (!
is_array($data)) {
   return
false;
  }
  return
$data;
}

public function
FetchAll($result) {
  if (
$this->connection === false) {
   die(
'No Database Connection Found.');
  }

 
$data = @sqlite_fetch_all($result);
  if (!
is_array($data)) {
   
$this->error = 'Fetch All Failed.';
   return
null;
  }
  return
$data;
}

function
table_exists($table) {

  return
sqlite_fetch_single($rez) > 0;
}
}
?>


index.php
<?php

// the following code will make it so that the class directory is in your include_path // this allows the __autoload function to work.
$cur = ini_get("include_path");
$cur .= PATH_SEPARATOR.dirname(__FILE__).'\\include\\class\\';;
ini_set("include_path", $cur);

// this will load any classes that are not found and are located in the // /include/class/ folder.

function __autoload($class) {
include(
$class . '.php');

/* Check to see it the include defined the class */  if ( !class_exists($class, false) ) {
 
trigger_error("Unable to load class $class", E_USER_ERROR);  } }

// get an instance of the sqlite database $db = Sqlite::getInstance('mysqlitedb', 0666); $db->Open(); $result = $db->Query('SELECT * FROM states'); $arr = $db->FetchAll($result);

echo '<pre>';
print_r($arr);
echo
'</pre>';

/*
// this is how you would use the Mysql class

$db1 = Mysql::getInstance('localhost', 'mydb', 'user', 'password'); $db1->Open(); $result = $db1->Query("SELECT * FROM table");
$arr1 = $db1->FetchArray($result);

echo '<pre>';
print_r($arr1);
echo '</pre>';
*/
?>




very simple ftp class
Categories : PHP, PHP Classes, FTP
PHP Paypal IPN Integration Class v1.0.0
Categories : PHP, PHP Classes, Payment Gateways
A Timing Class
Categories : PHP, PHP Classes, Date Time
The class to check load time of your script VERY usefull for relatively slow applications, but not only..
Categories : PHP, PHP Classes, Debugging
Create HTML forms dynamicly using Javascript & PHP
Categories : PHP, PHP Classes, Java Script
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables
RSS parser. Parses RSS into an array. Quick and nasty but does the job. No checking is done for correct Tags, only correct XML. PHP4 needed to display result (uses print_r).
Categories : PHP, XML, PHP Classes, Rich Site Summary (RSS)
These PHP Classes Check if a host is alive using various methods.
Categories : PHP, PHP Classes, Sockets, CURL
an example of the cyberlib payment class
Categories : PHP, PHP Classes, Ecommerce, Credit Cards
Power Form Validation
Categories : PHP, PHP Classes, Data Validation
MySQL Handler
Categories : PHP, Databases, MySQL, Classes and Objects, PHP Classes
pcCalendar class - Allows for the creation of calendars in HTML pages. All output functions can be easily overridden, refer to article 1471 for an example.
Categories : PHP, Date Time, Calendar, PHP Classes
Class for sending mail with MIME attachments in multipart format using external sendmail, mimencode and zip
Categories : Email, Network, PHP, PHP Classes
A PHP Calendar function with CSS : add a cool calendar to any php page by just adding a calendar class based function.
Categories : PHP, PHP Classes, Calendar, Date Time
Browser Detecor Class
Categories : PHP Classes, PHP, HTML
 Simon Hedberg wrote : 1185
I`m also thinking of implementing something like this..  It was interesting to see your code. 
I know however that the __construct function should be private since you should only be able to create instances from the getInstance method.
Check out http://www.phppatterns.com for more info on different patterns.
 
 Joseph Crawford wrote : 1186
very correct, the constructors for the Mysql and Sqlite should be private however the constructor for the database class should have been protected.

thanks for finding that error ;)

Joe
 
 Joseph Crawford wrote :1187
i have also found out that you should make the classes final so that they cannot be extended such as

final class Mysql {

}

etc..