Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can instantiate your connection to the database in a class that implement the singleton pattern. The connection will be done once and this class will be easily accessible by all of your other objects / scripts.</p> <p>i use a class called "Core" in the following example;</p> <pre><code>class Core { public $dbh; // handle of the db connexion private static $instance; private function __construct() { // building data source name from config $dsn = 'pgsql:host=' . Config::read('db.host') . ';dbname=' . Config::read('db.basename') . ';port=' . Config::read('db.port') . ';connect_timeout=15'; // getting DB user from config $user = Config::read('db.user'); // getting DB password from config $password = Config::read('db.password'); $this-&gt;dbh = new PDO($dsn, $user, $password); } public static function getInstance() { if (!isset(self::$instance)) { $object = __CLASS__; self::$instance = new $object; } return self::$instance; } // others global functions } </code></pre> <p>this class take parameters from a static class called "Config" where you can store your configuration:</p> <pre><code>&lt;?php class Config { static $confArray; public static function read($name) { return self::$confArray[$name]; } public static function write($name, $value) { self::$confArray[$name] = $value; } } // db Config::write('db.host', '127.0.0.1'); Config::write('db.port', '5432'); Config::write('db.basename', 'mydb'); Config::write('db.user', 'myuser'); Config::write('db.password', 'mypassword'); </code></pre> <p>in all your scripts / objects you just have to get the instance of Core and then query the DB</p> <pre><code>$sql = "select login, email from users where id = :id"; try { $core = Core::getInstance(); $stmt = $core-&gt;dbh-&gt;prepare($sql); $stmt-&gt;bindParam(':id', $this-&gt;id, PDO::PARAM_INT); if ($stmt-&gt;execute()) { $o = $stmt-&gt;fetch(PDO::FETCH_OBJ); // blablabla.... </code></pre> <p>If you need more information about singleton look at the PHP doc <a href="http://php.net/manual/en/language.oop5.patterns.php" rel="noreferrer">http://php.net/manual/en/language.oop5.patterns.php</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload