<?php
//-----config--------------------------------------//
$dbHost = 'localhost'; $dbName = 'aaa'; $dbUser = 'root'; $dbPass = '';
//--------------------------------------------------//
class database{ private $dbObj = false; private $dbHost = false; private $dbName = false; private $dbUser = false; private $dbPass = false;
function __construct($dbHost, $dbName, $dbUser, $dbPass){ $this->dbHost = $dbHost; $this->dbName = $dbName; $this->dbUser = $dbUser; $this->dbPass = $dbPass; while(!$this->connect()){ sleep(1); echo "初始化数据库连接失败\n"; }; }
public function connect(){ try{ $this->dbObj = new PDO("mysql:host={$this->dbHost};dbname={$this->dbName};charset=UTF8", $this->dbUser, $this->dbPass, Array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'UTF8';")); $this->dbObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return true; }catch(PDOException $e){ return false; } }
public function query($sql, $type = 'array'){ //$sql = $this->dbObj->quote($sql); try{ switch($type){ case 'array': $dbObj = $this->dbObj->query($sql); if(!$dbObj) return false; $result = $dbObj->fetchAll(PDO::FETCH_ASSOC); break; case 'row': $dbObj = $this->dbObj->query($sql); if(!$dbObj) return false; $result = $dbObj->fetch(PDO::FETCH_ASSOC); break; case 'exec': $result = $this->dbObj->exec($sql); break; } if($result) return $result; else return Array();
}catch(PDOException $e){ if($e->errorInfo[0] == 70100 || $e->errorInfo[0] == 2006){ $count = 0; while(!$this->connect()){ sleep(1); echo "数据库重新连接失败(try:{$count})\n"; $count++; }; return $this->query($sql, $type); }else exit($e->errorInfo[2]); } }
public function insert($table, $insertArray){ //单引号问题 $columns = array_keys($insertArray); $values = array_values($insertArray); unset($insertArray); foreach($values as $key => $value) $values[$key] = $this->dbObj->quote($value); foreach($columns as $key => $value) $columns[$key] = "{$table}.{$value}"; $columns = implode(',', $columns); $values = implode(',', $values); $query = "INSERT INTO {$table} ({$columns}) VALUES ({$values})"; return $this->query($query, 'exec'); }
public function update($table, $updateArray, $where){ $updates = Array(); foreach ($updateArray as $key => $value){ if($value != NULL) $updates[] = $key.'='.$this->dbObj->quote($value); else $updates[] = $key.'= NULL'; } unset($updateArray); $updates = implode(',', $updates); $query = "UPDATE {$table} SET {$updates} WHERE {$where}"; // echo $query; return $this->query($query, 'exec'); }
public function del($table, $where){ $query = "DELETE FROM $table WHERE {$where}"; return $this->query($query, 'exec'); }
public function insertId(){ return $this->dbObj->lastInsertId(); }
public function quote($value){ return $this->dbObj->quote($value); } }
$db = new database($dbHost, $dbName, $dbUser, $dbPass);
?>
|
请发表评论