Esta pregunta es muy antigua, pero estará bien si contribuyo. Creo que necesita implementar una clase singleton para manejar las conexiones de la base de datos. Escribiré una clase de muestra a continuación.
<?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
?>
Nuestra clase singleton solo puede hacer una conexión y reutilizarla, veamos cómo podemos usar nuestra clase
<?php
$dbh = DB::connect();
foreach ($dbh->query('SELECT * from agent') as $row){
print_r($row);
}
?>