WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
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 Resources
Web Development Content
Internet Security Software
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
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

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 : 1 of 5 (graded 3 times)
Viewed : 21751
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

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

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>';
*/
?>




Remote Archive (Zip, Tar, Gzip) downloader with FTP and local extration support
Categories : PHP, FTP, Filesystem, PHP Classes, Compression
DbObject - A PHP wrapper for working with various databases
Categories : Databases, PHP, PHP Classes
Authorize.net AIM Interface Class v1.0.0
Categories : PHP, PHP Classes, Ecommerce, Payment Gateways
Browser Detecor Class
Categories : PHP Classes, PHP, HTML
filesplit : Split big text files in multiple small ones
Categories : PHP, Log Files, Filesystem, PHP Classes
A File Browser Class.To Read Drives,Directories and Files .Files writing is also possible
Categories : PHP, PHP Classes, Filesystem
Specify your connection settings and create a link to a MySQL database.
Categories : PHP, PHP Classes, Databases, MySQL, Beginner Guides
Filter - A simple class that lets you use multiple functions to create custom filters.
Categories : PHP, PHP Classes, Strings
Customizable Calendar Class
Categories : HTML and PHP, Date Time, PHP, PHP Classes, Calendar
HTML_Graphs uses PHP to provide a consistent interface for creating HTML based charts. The user of the class sets up arrays that are passed to html_graph() which then takes care of all the messy HTML layout.
Categories : Graphics, Arrays, PHP, PHP Classes, Charts and Graphs
Simple and fast user authentication
Categories : PHP, PHP Classes, Authentication
Client classes for Dictionary servers UPDATED: 2000-06-06
Categories : Network, Search, Complete Programs, PHP Classes, PHP
file class , uploade file , download file already uploaded on another website
Categories : PHP, PHP Classes, Filesystem, Web Services
Bs_IniHandler is a class that can read and write ini-style files (and strings)
Categories : PHP, Filesystem, PHP Classes
Array Insertion
Categories : PHP, PHP Classes, Arrays
 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..