Best way to make mysql PDO static connection class?

I am new to PDO, as well as OOP with PHP in general, so please be beautiful :) Basically, I am trying to create a connection object based on PDO so that I have one connection that I call on my site.

I need prepared statements that just look for different results based on the identifier that I am viewing using the same db object that I am trying to create below.

How can I make and access the db class set below and then use the functions in it to extract the information I need? Any examples would be great, so I could get an idea of ​​best practices, etc.

Thank you very much in advance.

class db { private static $connection; private function __construct(){} private function __clone(){} private static function connect($db_server="localhost", $db_user="user", $db_pass="password") { if(!$this->connection){ try{ $this->connection = new PDO($db_server, $db_user, $db_pass); } catch (PDOException $e) { $this->connection = null; die($e->getMessage()); } } return $this->connection; } } $dbh = new db::connect(); $stmt = $dbh->prepare("SELECT * FROM questions where id = ?"); if($stmt->execute(array($_REQUEST['testid']))) { while ($row = $stmt->fetch()) { print_r($row); } } 
+7
source share
2 answers

You can start by never using the Singleton template. This (and static classes in general) is bad for all of the same reasons why global variables in procedural programming are bad.

That says ... Instead of trying to ensure the uniqueness of the connection object, you just have to make sure that you use the same connection everywhere.

Here is an example of what I mean:

 class Foo { protected $connection = null; public function __construct( PDO $connection ) { $this->connection = $connection; } } class Bar { // all the same as in Foo } $connection = new PDO('sqlite::memory'); $foo = new Foo( $connection ); $bar = new Bar( $connection ); 

At this point, the objects $foo and $bar will have access to the PDO instance of the same . If you have an object that needs access to the database, you simply provide it with a connection in the constructor.

There are two videos you can watch (the slides will contain Java code, but you should not understand it):

+5
source

Permanent connections are built in:

 $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array( PDO::ATTR_PERSISTENT => true )); 

See Example # 4 Persistent Connections

0
source

All Articles