PHP 简单的MySQL包装PDO

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 简单的MySQL包装PDO相关的知识,希望对你有一定的参考价值。

<?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)
		{
			return forward_static_call_array(array(self::$DB, $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']
			);

			
?>

以上是关于PHP 简单的MySQL包装PDO的主要内容,如果未能解决你的问题,请参考以下文章

php 使用CRUD方法的简单而安全的PHP PDO数据库包装器......

如何使用 PHP PDO 解析 MySQL 数据库中的对象数据?

使用 php、pdo 和 mysql 显示当前登录用户的简单计数器

PHP实现的pdo连接数据库并插入数据功能简单示例

如何在PHP下开启PDO MySQL的扩展

如何在PHP下开启PDO MySQL的扩展