- 論壇徽章:
- 0
|
早前寫過一片文章《
利用正則表達式加快開發(fā)
》 ,開發(fā)速度快了不少,不過項目復(fù)雜了,發(fā)現(xiàn)缺點很多,且對結(jié)構(gòu)清晰和可讀性沒有任何幫助,于是在新項目中就寫了這個數(shù)據(jù)操作基類,專門負責(zé)數(shù)據(jù)的插入更新等操作。
使用過adodb的朋友,一定很熟悉里面的兩個方法:getInsertSql()和getUpdateSql(),是根據(jù)數(shù)組生成sql語句用的。在復(fù)雜的項目,使用這兩個方法帶來的好處顯而意見。
我寫的這個類是adodb_lite版本的,改成適用其他數(shù)據(jù)庫類也不難。當(dāng)然也可以直接參考里面的方法,寫一個適用自己情況的類。
該類的基本代碼general_sql.class.php:
class GeneralSql
{
var $dbtableMessages;//數(shù)據(jù)表名稱
var $db;//數(shù)據(jù)庫連接對象
var $debugging = DEBUG_MODE; //調(diào)試模式:TRUE是開啟,F(xiàn)ALSE時關(guān)閉
//構(gòu)造函數(shù)
function GeneralSql($dsn, $dbtableMessages='table_name')
{
$this->db =& get_dbobject($dsn); //get_dbobject() 方法是獲得一個數(shù)據(jù)庫連接,代碼可參考附錄
$this->dbtableMessages = $dbtableMessages;
}
###########擴展數(shù)據(jù)操作函數(shù)####################
//在一個表中插入多個數(shù)據(jù)
function multiInsert ($array,$table=0)
{
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
if ( !( $this->insert($value,$table) ) )
return false;//如果插入失敗,就返回
}
}
return true;
}
//插入一條數(shù)據(jù)
function insert ($array,$table=0)
{
$sql = $this->getInsertSql($array,$table);
$this->db->Query($sql);
$results = $this->db->Insert_ID();
if($results > 0)
return $results;
else if ( $this->debugging )
{
echo '
SQL語句為:'.$sql.'
';
die($this->db->ErrorMsg());
}else
return 0;
}
//在多個表中更新同樣的字段
function multiUpdate($array,$where)
{
foreach ( $where as $key => $value )//此處$key為表名,$value為條件數(shù)組。
{
if ( !($this->update($array,$value,$key)) )
return false;
}
return true;
}
//一般更新方式,只要語法合法就會返回成功
function update ($array,$where,$table=0)
{
$sql = $this->getUpdateSql($array,$where,$table);
$this->db->Query("set names 'utf8'");
$results=$this->db->Query($sql);
if($results)
return true;
else if ( $this->debugging )
{
echo '
sql語句為:'.$sql.'
';
die($this->db->ErrorMsg());
}else
return false;
}
//嚴格更新方式,即只有數(shù)據(jù)更新了才返回成功
function strictUpdate ($array,$where,$table=0)
{
$sql = $this->getUpdateSql($array,$where,$table);
$this->db->Query($sql);
$results = $this->db->Affected_Rows();
if($results)
return true;
else if ( $this->debugging )
{
echo '
sql語句為:'.$sql.'
';
die($this->db->ErrorMsg());
}else
return false;
}
//返回數(shù)據(jù)插入語句
function &getInsertSql ($data,$table=0)
{
$sql_head = '';
$sql_end ='';
if ( is_array( $data ) )
{
foreach ( $data as $key => $value )
{
$sql_head .= "`" . $key . "`,";
if ( is_int( $value ) )//是整數(shù)的情況
{
$sql_end .= $value . ",";
}else if ( is_string( $value ) )//是字符串的情況
{
$sql_end .= "'" . $value . "',";
}else//其他情況
{
$sql_end .= "'" . $value . "',";
}
}
if ( $table )
{
$sql = 'insert into '.$table.' (' . subStr( $sql_head,0,-1 ) .') values ('. subStr( $sql_end,0,-1) . ')';
}else
{
$sql = 'insert into '.$this->dbtableMessages.' (' . subStr( $sql_head,0,-1 ) .') values ('. subStr( $sql_end,0,-1) . ')';
}
}else
die('insert error: $data is not an array!');
return $sql;
}
//返回數(shù)據(jù)更新語句
function &getUpdateSql ($data,$where,$table=0)
{
$sql_head = '';
$sql_end = '';
if ( is_array( $data ) )
{
foreach ( $data as $key => $value )
{
$sql_head .= "`" . $key ."`=";
if ( is_int( $value ) )//是整數(shù)的情況
{
$sql_head .= $value . ',';
}else if ( is_string( $value ) )//是字符串的情況
{
$sql_head .= "'" . $value . "',";
}else if ( is_array( $value ) )//用來處理特別情況,比如 friends = friends+1 這種。
{
$sql_head .= $value[0] . ',';
}else//其他情況
{
$sql_head .= "'" . $value . "',";
}
}
}else
die('update error: $data is not an array');
if ( is_array( $where ) )
{
foreach ( $where as $key => $value )
{
if ( subStr( $key,0,6 ) == '#conj#' )//連接詞(比如and 或者 or),用來處理多個條件的情況
{
$sql_end .=' ' . $value . ' ';
}else
{
$sql_end .= "`" . $key . "`=";
if ( is_int( $value ) )//是整數(shù)的情況
{
$sql_end .= $value;
}else if ( is_string( $value ) )//是字符串的情況
{
$sql_end .= "'" . $value . "'";
}else//其他情況
{
$sql_end .= "'" . $value . "'";
}
}
}
}else
die('update error: $where is not an array');
if ( $table )
{
$sql = 'update ' . $table . ' set ' . subStr( $sql_head,0,-1 ) . ' where ' . $sql_end;
}else
{
$sql = 'update ' . $this->dbtableMessages . ' set ' . subStr( $sql_head,0,-1 ) . ' where ' . $sql_end;
}
return $sql;
}
}
?>
說明:其中構(gòu)造函數(shù)中用到 get_dbobject() 方法是獲得一個數(shù)據(jù)庫連接,在附錄有源代碼。
大概用法:
1 在主配置文件,或者相應(yīng)的php程序中添加:
define( 'DEBUG_MODE',TRUE );//測試模式
include_once( './includes/general_sql.class.php' );
2 比如有一用戶數(shù)據(jù)表user,含有user_id(主鍵),nickname,name,birdathday...等等字段。
那么相應(yīng)的user操作類為:
db =& get_dbobject($dsn);
$this->dbtableMessages = $dbtableMessages;
}
......//其他user方法,如查詢等等
?>
那么在程序,我們?nèi)绻迦胍恍碌挠脩簦瑒t只需:
$user = new User(DB_DSN,'user');//DB_DSN為數(shù)據(jù)庫連接用的 DSN 字符串,可參考附錄
$data = $array(
'nickname' => $nickname,
'name' => $name,
'birdathday' => $birdathday,
//其他字段......
);
if($user->insert($data))
{
//用戶插入成功
}
相應(yīng)的,更新操作為:
$data2 = array(
'nickname' => $nickname,
'name' => $name,
'birdathday' => $birdathday,
//其他字段......
);
$where2 = array(
'user_id' => $user_id,
'#conj#' => 'and',
'status' => 1,
);
if($user->strictUpdate($data2,$where2))
{
//用戶信息更新成功
}
當(dāng)然如果只有上訴幾個字段,那大可不必用該類,但是如果是在字段很多的情況下,且開發(fā)時間很緊的情況,那么使用這種方式可以大大的加快開發(fā)速度,最重要的是,結(jié)構(gòu)的清晰,使得修改和增加功能都變得非常方便。該類的還有兩個方法如:在一個表中插入多個數(shù)據(jù)(multiInsert) 和 在多個表中更新同樣的字段(multiUpdate),是根據(jù)我自己的需求所寫的,就不詳細介紹了。
最后,當(dāng)然如果您使用的是adodb,那么自然不用看該類啦,呵呵
附錄:
數(shù)據(jù)庫連接配置文件:
define('DB_HOST', '192.168.0.1:3306');// 數(shù)據(jù)庫所在服務(wù)器
define('DB_NAME', 'test');// 數(shù)據(jù)庫名稱
define('DB_USER', 'root');// 數(shù)據(jù)庫連接用戶名
define('DB_PASS', '');// 數(shù)據(jù)庫連接密碼
define('DB_DSN', DB_TYPE . '://' . DB_USER . ':' . DB_PASS .
[email='@']'@'[/email]
. DB_HOST . '/' . DB_NAME); // DSN 字符串
/**
* 分析 DSN 字符串
* 如果成功返回分析結(jié)果,失敗返回 false
* @param string $dsn 要分析的 dsn 字符串
* @return array|boolean
*/
function parse_dsn($dsn) {
$dsn = str_replace('@/',
[email='@localhost/']'@localhost/'[/email]
, $dsn);
$parse = parse_url($dsn);
if (empty($parse['scheme'])) { return false; }
$dsn = array();
$dsn['host'] = $parse['host'];
$dsn['port'] = $parse['port'];
$dsn['user'] = $parse['user'];
if(array_key_exists('pass',$parse))
$dsn['pass'] = $parse['pass'];
else
$dsn['pass'] = '';
$dsn['driver'] = strtolower($parse['scheme']);
$dsn['dbname'] = (isset($parse['path'])) ? substr($parse['path'], 1) : '';
$dsn['options'] = (isset($parse['query'])) ? $parse['query'] : '';
return $dsn;
}
/**
* 獲得數(shù)據(jù)庫連接對象
* @return object
* @access public
*/
function & get_dbobject($dsnString = DB_DSN) {
static $instances = array();
if (isset($instances[$dsnString])) { return $instances[$dsnString]; }
if (!($dsn = parse_dsn($dsnString))) { return false; }
require_once(ADOLITE_PATH . '/adodb.inc.php');
$instances[$dsnString] = ADONewConnection($dsn['driver']);
if (!$instances[$dsnString]->Connect($dsn['host'].":3307", $dsn['user'], $dsn['pass'], $dsn['dbname'])) {
die("數(shù)據(jù)庫錯誤:" . __FILE__ . ':' . __LINE__ . "\n" . "Can't connectio to database: {$dsn['dbname']}\n" . "username and host: {$dsn['user']}@{$dsn['host']}\n");
}
$instances[$dsnString]->SetFetchMode(ADODB_FETCH_ASSOC);
if (strtolower(substr($dsn['driver'], 0, 5)) == 'mysql') {
$version = $instances[$dsnString]->GetOne('SELECT VERSION()');
if ($version >= '4.1') {
$instances[$dsnString]->Execute("SET NAMES 'latin1'");
//該處視自己的字符集設(shè)定而定。MYSQL版本4.1版本以下無需考慮
}
}
return $instances[$dsnString];
}
?>
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u/12569/showart_181603.html |
|