UCHOME二次開發之數據庫操作原理

作者:和奇一號發表于:2012-11-16

class_mysql.php,數據庫操作文件
dbstuff類中最重要的方法就是connect()和query()方法,connect負責開啓數據庫連接,具體取數據就靠query了,query的核心代碼如下:
$func = $type == ‘UNBUFFERED’ && @function_exists(‘mysql_unbuffered_query’) ?
            ‘mysql_unbuffered_query’ : ‘mysql_query’;
        if(!($query = $func($sql, $this->link)) && $type != ‘SILENT’) {
            $this->halt(‘MySQL Query Error’, $sql);
        }
聲明變量$func,進行type判斷後,賦值爲“mysql_query”,然後$func(),就等于mysql_query().
query並不僅僅負責查詢,數據的插入和更新都是通過query來完成的,在function_common.php中:
//添加數據
function inserttable($tablename, $insertsqlarr, $returnid=0, $replace = false) {
    global $_SGLOBAL;

    $insertkeysql = $insertvaluesql = $comma = ”;
    foreach ($insertsqlarr as $insert_key => $insert_value) {
        $insertkeysql .= $comma.’`’.$insert_key.’`';
        $insertvaluesql .= $comma.’\”.$insert_value.’\”;
        $comma = ‘, ‘;
    }
    $method = $replace?’REPLACE’:'INSERT’;
    $_SGLOBAL['db']->query($method.’ INTO ‘.tname($tablename).’ (‘.$insertkeysql.’) VALUES (‘.$insertvaluesql.’) ‘);
    if($returnid && !$replace) {
        return $_SGLOBAL['db']->insert_id();
    }
}

//更新數據
function updatetable($tablename, $setsqlarr, $wheresqlarr) {
    global $_SGLOBAL;

    $setsql = $comma = ”;
    foreach ($setsqlarr as $set_key => $set_value) {
        $setsql .= $comma.’`’.$set_key.’`’.’=\”.$set_value.’\”;
        $comma = ‘, ‘;
    }
    $where = $comma = ”;
    if(empty($wheresqlarr)) {
        $where = ‘1′;
    } elseif(is_array($wheresqlarr)) {
        foreach ($wheresqlarr as $key => $value) {
            $where .= $comma.’`’.$key.’`’.’=\”.$value.’\”;
            $comma = ‘ AND ‘;
        }
    } else {
        $where = $wheresqlarr;
    }
    $_SGLOBAL['db']->query(‘UPDATE ‘.tname($tablename).’ SET ‘.$setsql.’ WHERE ‘.$where);
}

//刪除數據
function_delete.php
$_SGLOBAL['db']->query(“DELETE FROM “.tname(‘comment’).” WHERE cid IN (“.simplode($newcids).”)”);