标签归档:数据库类 单例模式

利用单例模式写的连接数据库的类

根据单例模式和参考其他CMS里面的数据库类,整理了一个mysql数据库访问类

 
db=mysql_connect($dbHost,$dbUser,$dbPwd) or die(''Could not connect: ''.mysql_error());

$this->select_db($dbName); $this->query("SET NAMES $charset"); }

private function __clone(){} public static function get_instance($dbHost,$dbName,

$dbUser,$dbPwd,$charset) { if(!(self::$instance instanceof self)) { self::

$instance=new self($dbHost,$dbName,$dbUser,$dbPwd,$charset); } return self::

$instance; } /** *查询表 *返回一个一维数组 */ public function

get_one($sql) { $query = $this->query($sql); $rs = $this->fetch_array($query);

 $this->free_result($query); return $rs ; } /** *查询表 *返回一

个二维数组 */ public function select($sql, $keyfield = '''') { $array =

array(); $result = $this->query($sql); while($r = $this->fetch_array($result))

{ if($keyfield) { $key = $r[$keyfield]; $array[$key] = $r; } else

 { $array[] = $r; } } $this->free_result($result); return $array;

 } /** *修改数据 *@param tableName 操作的表 *@param array 信息数组

 *@param where 条件 */ function update($tableName,$array,$where = '''')

{ if($where) { $sql = ''''; foreach($array as $k=>$v) { $sql .= ",

`$k`=''$v''"; } $sql = substr($sql, 1); $sql = "UPDATE $tablename SET $sql

WHERE $where"; } else { $sql = "REPLACE INTO $tablename(`".implode(''`,`'',

array_keys($array))."`) VALUES(''".implode("'',''", $array)."'')"; } return $this-

>query($sql); } /** *添加数据 *@param tableName 操作的表 *@param

array 信息数组 *return int 信息id */ function insert($tableName, $array)

{ $this->query("INSERT INTO $tableName(`".implode(''`,`'', array_keys($array))."`)

VALUES(''".implode("'',''", $array)."'')"); return $this->insert_id(); }

public function query($sql) { return mysql_query($sql,$this->db); }

public function fetch_array($query, $result_type = MYSQL_ASSOC) { return

mysql_fetch_array($query, $result_type); } public function select_db

($dbName) { mysql_select_db($dbName , $this->db) or die(''Could not select

database''); $this->dbName =$dbName; } public function close() {

return mysql_close($this->db); } public function free_result(&$query) {

return mysql_free_result($query); } public function insert_id() {

return mysql_insert_id($this->db); } public function fetch_row($query) { return mysql_fetch_row($query); }  public function affected_rows() {

return mysql_affected_rows($this->db); } public function num_rows($query)

{ return mysql_num_rows($query); }}?>使用方法
$db=DbMySql::get_instance(''localhost'',''linji'',''root'',''12345678'',''utf8'');放在博客以便以后自己使用。', 0, 1, NULL, 'post', 'draft', NULL, 0, '1', '1', '1',
0);
Advertisements