使いやすいphp mysqlクラス(共有)

5529 ワード

<?php
/**
 * MySQL         ,        .
 *        .
 * @author: http://www.jbxue.com/ */
class Mysql{
    var $conn;
    var $query_list = array();
    public $query_count = 0;

    public function __construct($c){
        if(!isset($c['port'])){
            $c['port'] = '3306';
        }
        $server = $c['host'] . ':' . $c['port'];
        $this->conn = mysql_connect($server, $c['username'], $c['password'], true) or die('connect db error');
        mysql_select_db($c['dbname'], $this->conn) or die('select db error');
        if($c['charset']){
            mysql_query("set names " . $c['charset'], $this->conn);
        }
    }

    /**
     *    mysql_query       .
     */
    public function query($sql){
        $stime = microtime(true);

        $result = mysql_query($sql, $this->conn);
        $this->query_count ++;
        if($result === false){
            throw new Exception(mysql_error($this->conn)." in SQL: $sql");
        }

        $etime = microtime(true);
        $time = number_format(($etime - $stime) * 1000, 2);
        $this->query_list[] = $time . ' ' . $sql;
        return $result;
    }

    /**
     *    SQL   ,           (     ).
     */
    public function get($sql){
        $result = $this->query($sql);
        if($row = mysql_fetch_object($result)){
            return $row;
        }else{
            return null;
        }
    }

    /**
     *        ,   key          ,           .
     *    key   ,             .
     */
    public function find($sql, $key=null){
        $data = array();
        $result = $this->query($sql);
        while($row = mysql_fetch_object($result)){
            if(!empty($key)){
                $data[$row->{$key}] = $row;
            }else{
                $data[] = $row;
            }
        }
        return $data;
    }

    public function last_insert_id(){
        return mysql_insert_id($this->conn);
    }

    /**
     *              count SQL   ,      .
     */
    public function count($sql){
        $result = $this->query($sql);
        if($row = mysql_fetch_array($result)){
            return (int)$row[0];
        }else{
            return 0;
        }
    }

    /**
     *       .
     */
    public function begin(){
        mysql_query('begin');
    }

    /**
     *       .
     */
    public function commit(){
        mysql_query('commit');
    }

    /**
     *       .
     */
    public function rollback(){
        mysql_query('rollback');
    }

    /**
     *          .
     * @param int $id          .
     * @param string $field    ,    'id'.
     */
    function load($table, $id, $field='id'){
        $sql = "select * from `{$table}` where `{$field}`='{$id}'";
        $row = $this->get($sql);
        return $row;
    }

    /**
     *       ,    , id   .
     * @param object $row
     */
    function save($table, &$row){
        $sqlA = '';
        foreach($row as $k=>$v){
            $sqlA .= "`$k` = '$v',";
        }

        $sqlA = substr($sqlA, 0, strlen($sqlA)-1);
        $sql  = "insert into `{$table}` set $sqlA";
        $this->query($sql);
        if(is_object($row)){
            $row->id = $this->last_insert_id();
        }else if(is_array($row)){
            $row['id'] = $this->last_insert_id();
        }
    }

    /**
     *   $arr[id]      .
     * @param array $row       ,    id                .
     * @return int      .
     * @param string $field    ,    'id'.
     */
    function update($table, &$row, $field='id'){
        $sqlA = '';
        foreach($row as $k=>$v){
            $sqlA .= "`$k` = '$v',";
        }

        $sqlA = substr($sqlA, 0, strlen($sqlA)-1);
        if(is_object($row)){
            $id = $row->{$field};
        }else if(is_array($row)){
            $id = $row[$field];
        }
        $sql  = "update `{$table}` set $sqlA where `{$field}`='$id'";
        return $this->query($sql);
    }

    /**
     *       .
     * @param int $id         .
     * @return int      .
     * @param string $field    ,    'id'.
     */
    function remove($table, $id, $field='id'){
        $sql  = "delete from `{$table}` where `{$field}`='{$id}'";
        return $this->query($sql);
    }

    function escape(&$val){
        if(is_object($val) || is_array($val)){
            $this->escape_row($val);
        }
    }

    function escape_row(&$row){
        if(is_object($row)){
            foreach($row as $k=>$v){
                $row->$k = mysql_real_escape_string($v);
            }
        }else if(is_array($row)){
            foreach($row as $k=>$v){
                $row[$k] = mysql_real_escape_string($v);
            }
        }
    }

    function escape_like_string($str){
        $find = array('%', '_');
        $replace = array('\%', '\_');
        $str = str_replace($find, $replace, $str);
        return $str;
    }
}
?>
以上がphp mysqlクラスの呼び出し例:
<?php
//   
$db->save('table_1', $row);
//   
$db->update('table_1', $row);
//   
$db->remove('table_1', 1);
//   
$rows = $db->find($sql, 'id')
?>