围绕PDO的简单MySQL包装器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了围绕PDO的简单MySQL包装器相关的知识,希望对你有一定的参考价值。
A simple wrapper class for mysql around PDO. Also an example on how to use this wrapper for SQLite.
<?php // ------------------------------------------------------------------ // - Database class'es - // ------------------------------------------------------------------ /** * Main database class * Works as a layer over PDO. Every static call is forwarded to the PDO object, except for those which are defined * **/ class DB { protected static $DB; private function __construct() {} private function __clone() {} public static function connect($dbname='default', $host='localhost', $user='root', $password='') { try { // connects to the database self::$DB = new PDO("mysql:dbname=$dbname;host:=$host" , $user , $password); // set the error reporting attribute self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } } public static function close_connection() { self::$DB = NULL; } public static function __callStatic($name, $arguments) { } } /** * A test class * Using SQLite with 'sqlite::memory:' so that its no need for username, password, etc * Perfect for quick testing purpose * **/ class DBtest extends DB { public static function connect() { try { self::$DB = new PDO("sqlite::memory:"); // connect to database echo 'database created in memory <br /> <br />'; // only at debug mode - @TODO: remove it self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error reporting attribute } catch(PDOException $e) { echo $e->getMessage(); } } } // ------------------------------------------------------------------ // - Initilize a standard connection - // ------------------------------------------------------------------ include 'config.php'; $dbh::connect( $config['db']['default']['dbname'], $config['db']['default']['host'], $config['db']['default']['username'], $config['db']['default']['password'] ); ?>
以上是关于围绕PDO的简单MySQL包装器的主要内容,如果未能解决你的问题,请参考以下文章
php 使用CRUD方法的简单而安全的PHP PDO数据库包装器......