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); } }
Tim
source share