-7
<?php

//db connection class using singleton pattern
class dbConn {
    //variable to hold connection object.
    protected static $db;

    //private construct – class cannot be instatiated externally.
    private function __construct()
    {

        try { // assign PDO object to db variable
            self::$db = new PDO('mysql:host=localhost;dbname=cricket', 'root', '');
            setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) { //Output error – would normally log this to error file rather than output to user.
            echo "Connection Error: " . $e->getMessage();
        }
    }

    // get connection function. Static method – accessible without instantiation
    public static function getConnection()
    {
        //Guarantees single instance, if no connection object exists then create one.
        if (!self::$db) { //new connection object.
            new dbConn();
        }
    //return connection.
    return self::$db;
    }
}
//end class

?>

please check this error if i call this parameters in index like

    $sql = "select * from user";
    $q = dbConn::getConnection()->query($sql);

   $result =  $q->fetch();
    print_r($result);
}

tutorials link : http://weebtutorials.com/2012/03/pdo-connection-class-using-singleton-pattern/

Kazim King
  • 67
  • 1
  • 10
  • What error are you getting exactly? – Pekka Oct 22 '12 at 07:54
  • ( ! ) Fatal error: Class 'dbConn' not found in D:\xampp\htdocs\kazim\test2\index.php on line 4 Call Stack # Time Memory Function Location 1 0.0006 329488 {main}( ) ..\index.php:0 – Kazim King Oct 22 '12 at 07:57
  • i am flowwing this tutorial but its not working http://weebtutorials.com/2012/03/pdo-connection-class-using-singleton-pattern/ – Kazim King Oct 22 '12 at 07:59
  • That sounds like the connection class declaration is not present at runtime. If you use automatic inclusion (ClassPath) then maybe it is not stored in those paths. Or you simply forgot to include it... – arkascha Oct 22 '12 at 08:00
  • 3
    sidenote: [Who needs Singletons](http://stackoverflow.com/questions/4595964/who-needs-singletons/4596323#4596323) – Gordon Oct 22 '12 at 08:00
  • You must include the script file that class dbConn is defined in index.php. Add the following to the beginning of **index.php** : `include('dbConn.php');` – Ertunç Oct 22 '12 at 08:06
  • i include('dbConn.php'); it but not working – Kazim King Oct 22 '12 at 08:07
  • please test this tutotrial : http://weebtutorials.com/2012/03/pdo-connection-class-using-singleton-pattern/ – Kazim King Oct 22 '12 at 08:08

1 Answers1

6

Your code has several issues (aside from usefulness of singleton pattern in PHP):

The idea of a singleton is that the instance is referenced by a private static variable, which isn't the case in your code, you reference an instance of a PDO object. A true singleton version of your code would have to look like this:

class TrueSingleton
{
    private static $_instance;
    private $_pdo;

    private function __construct()
    {//private constructor:
        $this->_pdo = new PDO();//<-- connect here
        //You set attributes like so:
        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //not setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<-- PHP can't know which setAttribute method to call on what object
    }
    public static function getConnection()
    {
        if (self::$_instance === null)//don't check connection, check instance
        {
            self::$_instance = new TrueSingleton();
        }
        return self::$_instance;
    }
    //to TRULY ensure there is only 1 instance, you'll have to disable object cloning
    public function __clone()
    {
        return false;
    }
    public function __wakeup()
    {
        return false;
    }
}

The rest is pretty basic, apart from, whenever you need to query the DB, you'll have to use $this->_pdo->query() inside the member functions

Rob W
  • 9,134
  • 1
  • 30
  • 50
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • ( ! ) Fatal error: Class 'dbConn' not found in D:\xampp\htdocs\kazim\test2\index.php on line 4 – Kazim King Oct 22 '12 at 08:10
  • 1
    your Singleton misses `__wakeup()` which means it can be unserialized – Gordon Oct 22 '12 at 08:13
  • 1
    @KazimKing: does your index.php start with a line of code like `require_once('path/to/dbConn.php');` or does it contain a _working_ `__autoload()` function? PHP does need the class definition before it can use it, obviously. Check for typo's in the name, too. Also: don't use the `?>` closing tag in php class definition files – Elias Van Ootegem Oct 22 '12 at 08:14
  • error in this code class TrueSingleton public static getConnection() - not working – Kazim King Oct 22 '12 at 08:15
  • not working – Kazim King Oct 22 '12 at 08:18
  • @KazimKing: well obviously, the constructor isn't a working example, and the `self::$_instance` variable isn't properly initialized to null. You'll have to add some of your own code to get this working – Elias Van Ootegem Oct 22 '12 at 08:19
  • @KazimKing: Have you defined this class in a file called `dbConn.php`, and is it in the same directory as `index.php`? if not: then it stands to reason that php can't find it. Read [the require_once docs](http://www.php.net/require_once), or write [an autoloader function](http://php.net/manual/en/function.autoload.php) – Elias Van Ootegem Oct 22 '12 at 08:21
  • all files in same folder – Kazim King Oct 22 '12 at 09:40