This question is very old, but everything will be fine if I contributed. I think you need to implement a singleton class to handle database connections. I will write a sample class below.
<?php class DB{ //set the connection property to private to prevent direct access private static $conn; //now since we dont want to reinstiate the class anytime we need it, lets also set the constructor to private private function __construct(){} //now lets create our method for connecting to the database public static function connect(){ //now lets check if a connection exists already in our $conn property, then we should return it instead of recreating a new connection if(!empty(self::$conn)){ return self::$conn; }//end if //upon reaching here means the $conn property is empty so lets create a new connection try { $dbh = new PDO('mysql:host=127.0.0.1;dbname=lingtong', 'root', 'xxxxxx', array(PDO::ATTR_PERSISTENT => true)); //lets now assign the database connection to our $conn property self::$conn = $dbh; //return the connection return $dbh; } catch (PDOException $e) { print "Error! : " . $e->getMessage() . "<br/>"; die(); } }//end method }//end class ?>
Our singleton class can only make one connection and reuse it, see how we can use our class
<?php $dbh = DB::connect(); foreach ($dbh->query('SELECT * from agent') as $row){ print_r($row); } ?>
razzbee
source share