开发者

Method for Using PDO in PHP

开发者 https://www.devze.com 2023-01-16 01:12 出处:网络
So I\'ve found a method which looked nice to me: http://www.php.net/manual/en/class.pdo.php#97682 Requires PHP 5.3 but my host onl开发者_C百科y supports 5.2 :(

So I've found a method which looked nice to me: http://www.php.net/manual/en/class.pdo.php#97682

Requires PHP 5.3 but my host onl开发者_C百科y supports 5.2 :(

So what method should I use for PDO, where it only connects to the database when needed? And reuses the same connection?


Use a procedural singleton for readability:

 function db() {
      static $conn;
      if (!isset($conn)) {
           $conn = new PDO("sqlite:/tmp/db");
      }
      return $conn;
 }

This simplifies the use to for example:

 $rows = db()->query("SELECT * FROM all")->fetchAll();


you can use singleton with instance. Database::getInstance() which creates, caches and returns PDO object


class db{

   protected static $conn;
   public static function getInstance() {

      if (!isset(self::$conn)) {
           self::$conn = new PDO("sqlite:/tmp/db");
      }

      return self::$conn;
   }
 }

$rows = db::getInstance()->query("SELECT * FROM all")->fetchAll();
0

精彩评论

暂无评论...
验证码 换一张
取 消