php封裝資料庫類
樓主整理代碼會好一點
2. php封裝一個class類實現mysql資料庫的增刪該查
<?php
class db{
private $db;
const MYSQL_OPT_READ_TIMEOUT = 11;
const MYSQL_OPT_WRITE_TIMEOUT = 12;
private $tbl_name;
private $where;
private $sort;
private $fields;
private $limit;
public static $_instance = null;
function __construct(){
$cfg = loadConfig('db');
$db = mysqli_init();
$db->options(self::MYSQL_OPT_READ_TIMEOUT, 3);
$db->options(self::MYSQL_OPT_WRITE_TIMEOUT, 1);
@$db->real_connect($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']);
if ($db->connect_error) {
$this->crash($db->errno,$db->error);
}
$db->set_charset("utf8");
$this->db = $db;
//echo $this->db->stat;
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
private function __clone() {} //覆蓋__clone()方法,禁止克隆
public function find($conditions = null){
if($conditions) $this->where($conditions);
return $this->getArray($this->buildSql(),1);
}
public function findAll($conditions = null){
if($conditions) $this->where($conditions);
return $this->getArray($this->buildSql());
}
//表
public function t($table){ $this->tbl_name = $table; return $this;}
//條件
public function where($conditions){
$where = '';
if(is_array($conditions)){
$join = array();
foreach( $conditions as $key => $condition ){
$condition = $this->db->real_escape_string($condition);
$join[] = "`{$key}` = '{$condition}'";
}
$where = "WHERE ".join(" AND ",$join);
}else{
if(null != $conditions) $where = "WHERE ".$conditions;
}
$this->where = $where;
return $this;
}
//排序
public function sort($sort){
if(null != $sort) $sort = "ORDER BY {$sort}";
$this->sort = $sort;
return $this;
}
//欄位
public function fields($fields){ $this->fields = $fields; return $this; }
public function limit($limit){$this->limit = $limit; return $this;}
private function buildSql(){
$this->fields = empty($this->fields) ? "*" : $this->fields;
$sql = "SELECT {$this->fields} FROM {$this->tbl_name} {$this->where} {$this->sort}";
accessLog('db_access',$sql);
if(null != $this->limit)$sql .= " limit {$this->limit}";
return $sql;
}
/**
* 返回查詢數據
* @param $sql
* @param bool $hasOne
* @return array|bool|mixed
*/
private function getArray($sql,$hasOne = false){
if($this->db->real_query($sql) ){
if ($result = $this->db->use_result()) {
$row = array();
if($hasOne){
$row = $result->fetch_assoc();
}else{
while($d = $result->fetch_assoc()) $row[] = $d;
}
$result->close();
$this->fields = "*";
return $row;
}else{
return false;
}
}else{
if($this->db->error){
$this->crash($this->db->errno,$this->db->error,$sql);
}
}
}
public function findSql($sql,$hasOne = false){
accessLog('db_access',$sql);
if($this->db->real_query($sql) ){
if ($result = $this->db->use_result()) {
$row = array();
if($hasOne){
$row = $result->fetch_assoc();
}else{
while($d = $result->fetch_assoc()) $row[] = $d;
}
$result->close();
$this->fields = "*";
return $row;
}else{
return false;
}
}else{
if($this->db->error){
$this->crash($this->db->errno,$this->db->error,$sql);
}
}
}
public function create($row){
if(!is_array($row))return FALSE;
$row = $this->prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key => $value){
$cols[] = '`'.$key.'`';
$vals[] = "'".$this->db->real_escape_string($value)."'";
}
$col = implode(',', $cols);
$val = implode(',', $vals);
$sql = "INSERT INTO `{$this->tbl_name}` ({$col}) VALUES ({$val})";
accessLog('db_access',$sql);
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
if($this->db->insert_id){
return $this->db->insert_id;
}
if($this->db->affected_rows){
return true;
}
}
return FALSE;
}
//直接執行sql
public function runSql($sql){
accessLog('db_access',$sql);
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
return true;
}else{
return false;
}
}
public function update($row){
$where = "";
$row = $this->prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key => $value){
$value = $this->db->real_escape_string($value);
$vals[] = "`{$key}` = '{$value}'";
}
$values = join(", ",$vals);
$sql = "UPDATE {$this->tbl_name} SET {$values} {$this->where}";
accessLog('db_access',$sql);
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
if( $this->db->affected_rows){
return true;
}
}
return false;
}
function delete(){
$sql = "DELETE FROM {$this->tbl_name} {$this->where}";
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
if( $this->db->affected_rows){
return true;
}
}
return FALSE;
}
private function prepera_format($rows){
$columns = $this->getArray("DESCRIBE {$this->tbl_name}");
$newcol = array();
foreach( $columns as $col ){
$newcol[$col['Field']] = $col['Field'];
}
return array_intersect_key($rows,$newcol);
}
//崩潰信息
private function crash($number,$message,$sql=''){
$msg = 'Db Error '.$number.':'.$message ;
if(empty($sql)){
echo t('db_crash');
}else{
$msg .= " SQL:".$sql;
echo t('db_query_err');
}
accessLog('db_error',$msg);
exit;
}
}
3. 最好用的PHP資料庫操作類-ezSQL
ezSQL是一個非常好用的PHP資料庫操作類 著名的開源博客WordPress的資料庫操作就使用了ezSQL的MySQL部分 該資料庫操作類支持幾乎所有主流的資料庫 如 PHP PDO mySQL Oracle InterBase/FireBird PostgreSQL SQLite以及MS SQL等 ezSQL具有很強的調試功能 可以快速地查看SQL代碼的執行情況 使用ezSQL 可以為我們節省開發時間 簡化代碼並提高運行效率
ezSQL的優點就不用多說了 它小巧 快速 簡單 易用 並且開源 還有就是安全 你沒想到的細節它都為你考慮了 你只需要在你的腳本開頭包含相關的PHP文件 然後你就可以使用更好用的一套ezSQL函數來代替標準的PHP資料庫操作函數
下面是ezSQL中一些主要的函數
$db >get_results 從資料庫中讀取數據集
$db >get_row 從資料庫中讀取一行數據
$db >get_col 從資料庫中讀取一列指定的數據集
$db >get_var 從資料庫的數據集中讀取一個值
$db >query 執行一條SQL語句
$db >debug 列印最後執行的SQL語句及其返回的結果
$db >varmp 列印變數的結構及其內容
$db >select 選擇一個新資料庫
$db >get_col_info 獲取列的信息
$db >hide_errors 隱藏錯誤
$db >show_errors 顯示錯誤
ezSQL的使用方法很簡單 首先下載ezSQL源代碼 然後將ez_sql_core php文件和ez_sql_mysql php文件(這里以mySQL為例)放到與你的腳本文件相同的目錄下 然後將下面的代碼添加到你的腳本文件的最前面 這樣就可以正常使用ezSQL了
<?php// 包含ezSQL的核心文件include_once"ez_sql_core php";// 包含ezSQL具體的資料庫文件 這里以mySQL為例include_once"ez_sql_mysql php";// 初始化資料庫對象並建立資料庫連接$db=newezSQL_mysql( db_user db_password db_name db_host );?>
下面是ezSQL中一些主要函數的應用實例 這些代碼均來自於ezSQL的官方幫助文檔
實例一
// Select multiple records from the database and print them out $users=$db >get_results("SELECT name email FROM users");foreach($usersas$user){ // Access data using object syntax echo$user >name; echo$user >email;}
實例二
// Get one row from the database and print it out $user=$db >get_row("SELECT name email FROM users WHERE id = ");echo$user >name;echo$user >email;
實例三
// Get one variable from the database and print it out $var=$db >get_var("SELECT count(*) FROM users");echo$var;
實例四
// Insert into the database$db >query("INSERT INTO users (id name email) VALUES (NULL justin jv@foo )");
實例五
// Update the database$db >query("UPDATE users SET name = Justin WHERE id = )");
實例六
// Display last query and all associated results$db >debug();
實例七
// Display the structure and contents of any result(s) or any variable$results=$db >get_results("SELECT name email FROM users");$db >varmp($results);
實例八
// Get one column (based on column index) and print it out $names=$db >get_col("SELECT name email FROM users" )foreach($namesas$name){ echo$name;}
實例九
// Same as above 『but quicker』foreach($db >get_col("SELECT name email FROM users" )as$name){ echo$name;}
實例十
lishixin/Article/program/PHP/201311/21297
4. PHP訪問MYSQL資料庫封裝類(附函數說明)
復制代碼
代碼如下:
<?php
/*
MYSQL
資料庫訪問封裝類
MYSQL
數據訪問方式,php4支持以mysql_開頭的過程訪問方式,php5開始支持以mysqli_開頭的過程和mysqli面向對象
訪問方式,本封裝類以mysql_封裝
數據訪問的一般流程:
1,連接資料庫
mysql_connect
or
mysql_pconnect
2,選擇資料庫
mysql_select_db
3,執行SQL查詢
mysql_query
4,處理返回的數據
mysql_fetch_array
mysql_num_rows
mysql_fetch_assoc
mysql_fetch_row
etc
*/
class
db_mysql
{
var
$querynum
=
0
;
//當前頁面進程查詢資料庫的次數
var
$dblink
;
//資料庫連接資源
//鏈接資料庫
function
connect($dbhost,$dbuser,$dbpw,$dbname='',$dbcharset='utf-8',$pconnect=0
,
$halt=true)
{
$func
=
empty($pconnect)
?
'mysql_connect'
:
'mysql_pconnect'
;
$this->dblink
=
@$func($dbhost,$dbuser,$dbpw)
;
if
($halt
&&
!$this->dblink)
{
$this->halt("無法鏈接資料庫!");
}
//設置查詢字元集
mysql_query("SET
character_set_connection={$dbcharset},character_set_results={$dbcharset},character_set_client=binary",$this->dblink)
;
//選擇資料庫
$dbname
&&
@mysql_select_db($dbname,$this->dblink)
;
}
//選擇資料庫
function
select_db($dbname)
{
return
mysql_select_db($dbname,$this->dblink);
}
//執行SQL查詢
function
query($sql)
{
$this->querynum++
;
return
mysql_query($sql,$this->dblink)
;
}
//返回最近一次與連接句柄關聯的INSERT,UPDATE
或DELETE
查詢所影響的記錄行數
function
affected_rows()
{
return
mysql_affected_rows($this->dblink)
;
}
//取得結果集中行的數目,只對select查詢的結果集有效
function
num_rows($result)
{
return
mysql_num_rows($result)
;
}
//獲得單格的查詢結果
function
result($result,$row=0)
{
return
mysql_result($result,$row)
;
}
//取得上一步
INSERT
操作產生的
ID,只對表有AUTO_INCREMENT
ID的操作有效
function
insert_id()
{
return
($id
=
mysql_insert_id($this->dblink))
>=
0
?
$id
:
$this->result($this->query("SELECT
last_insert_id()"),
0);
}
//從結果集提取當前行,以數字為key表示的關聯數組形式返回
function
fetch_row($result)
{
return
mysql_fetch_row($result)
;
}
//從結果集提取當前行,以欄位名為key表示的關聯數組形式返回
function
fetch_assoc($result)
{
return
mysql_fetch_assoc($result);
}
//從結果集提取當前行,以欄位名和數字為key表示的關聯數組形式返回
function
fetch_array($result)
{
return
mysql_fetch_array($result);
}
//關閉鏈接
function
close()
{
return
mysql_close($this->dblink)
;
}
//輸出簡單的錯誤html提示信息並終止程序
function
halt($msg)
{
$message
=
"<html>\n<head>\n"
;
$message
.=
"<meta
content='text/html;charset=gb2312'>\n"
;
$message
.=
"</head>\n"
;
$message
.=
"<body>\n"
;
$message
.=
"資料庫出錯:".htmlspecialchars($msg)."\n"
;
$message
.=
"</body>\n"
;
$message
.=
"</html>"
;
echo
$message
;
exit
;
}
}
?>
5. 求PHP資料庫封裝類操作代碼
<?php
class MySQL{
private $host; //伺服器地址
private $name; //登錄賬號
private $pwd; //登錄密碼
private $dBase; //資料庫名稱
private $conn; //資料庫鏈接資源
private $result; //結果集
private $msg; //返回結果
private $fields; //返回欄位
private $fieldsNum; //返回欄位數
private $rowsNum; //返回結果數
private $rowsRst; //返回單條記錄的欄位數組
private $filesArray = array(); //返回欄位數組
private $rowsArray = array(); //返回結果數組
private $charset='utf8'; //設置操作的字元集
private $query_count=0; //查詢結果次數
static private $_instance; //存儲對象
//初始化類
private function __construct($host='',$name='',$pwd='',$dBase=''){
if($host != '') $this->host = $host;
if($name != '') $this->name = $name;
if($pwd != '') $this->pwd = $pwd;
if($dBase != '') $this->dBase = $dBase;
$this->init_conn();
}
//防止被克隆
private function __clone(){}
public static function getInstance($host='',$name='',$pwd='',$dBase=''){
if(FALSE == (self::$_instance instanceof self)){
self::$_instance = new self($host,$name,$pwd,$dBase);
}
return self::$_instance;
}
public function __set($name,$value){
$this->$name=$value;
}
public function __get($name){
return $this->$name;
}
//鏈接資料庫
function init_conn(){
$this->conn=@mysql_connect($this->host,$this->name,$this->pwd) or die('connect db fail !');
@mysql_select_db($this->dBase,$this->conn) or die('select db fail !');
mysql_query("set names ".$this->charset);
}
//查詢結果
function mysql_query_rst($sql){
if($this->conn == '') $this->init_conn();
$this->result = @mysql_query($sql,$this->conn);
$this->query_count++;
}
//取得欄位數
function getFieldsNum($sql){
$this->mysql_query_rst($sql);
$this->fieldsNum = @mysql_num_fields($this->result);
}
//取得查詢結果數
function getRowsNum($sql){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
return @mysql_num_rows($this->result);
}else{
return '';
}
}
//取得記錄數組(單條記錄)
function getRowsRst($sql,$type=MYSQL_BOTH){
$this->mysql_query_rst($sql);
if(empty($this->result)) return '';
if(mysql_error() == 0){
$this->rowsRst = mysql_fetch_array($this->result,$type);
return $this->rowsRst;
}else{
return '';
}
}
//取得記錄數組(多條記錄)
function getRowsArray($sql,$type=MYSQL_BOTH){
!empty($this->rowsArray) ? $this->rowsArray=array() : '';
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
while($row = mysql_fetch_array($this->result,$type)) {
$this->rowsArray[] = $row;
}
return $this->rowsArray;
}else{
return '';
}
}
//更新、刪除、添加記錄數
function uidRst($sql){
if($this->conn == ''){
$this->init_conn();
}
@mysql_query($sql);
$this->rowsNum = @mysql_affected_rows();
if(mysql_errno() == 0){
return $this->rowsNum;
}else{
return '';
}
}
//返回最近插入的一條資料庫的id值
function returnRstId($sql){
if($this->conn == ''){
$this->init_conn();
}
@mysql_query($sql);
if(mysql_errno() == 0){
return mysql_insert_id();
}else{
return '';
}
}
//獲取對應的欄位值
function getFields($sql,$fields){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
if(mysql_num_rows($this->result) > 0){
$tmpfld = @mysql_fetch_row($this->result);
$this->fields = $tmpfld[$fields];
}
return $this->fields;
}else{
return '';
}
}
//錯誤信息
function msg_error(){
if(mysql_errno() != 0) {
$this->msg = mysql_error();
}
return $this->msg;
}
//釋放結果集
function close_rst(){
mysql_free_result($this->result);
$this->msg = '';
$this->fieldsNum = 0;
$this->rowsNum = 0;
$this->filesArray = '';
$this->rowsArray = '';
}
//關閉資料庫
function close_conn(){
$this->close_rst();
mysql_close($this->conn);
$this->conn = '';
}
//取得資料庫版本
function db_version() {
return mysql_get_server_info();
}
}