027-87227388

UCHOME二次开发之数据库操作原理

发布时间:2012-11-16 浏览:2475

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).”)”);