Dette spørgsmål er meget gammelt, men det vil være okay, hvis jeg bidrager. Jeg tror, du skal implementere en singleton-klasse til at håndtere databaseforbindelser, jeg vil skrive en prøveklasse nedenfor ..
<?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
?>
Vores singleton-klasse kan kun oprette én forbindelse og genbruge den, lad os se, hvordan vi kan bruge vores klasse
<?php
$dbh = DB::connect();
foreach ($dbh->query('SELECT * from agent') as $row){
print_r($row);
}
?>