db_mysqli

<?php
/**
 * 數據庫操作
 */
 
$root_dir_mysqli = dirname(__FILE__);
include_once $root_dir_mysqli.'/file.php';
 
class DbMysqliOperation{
    
    //數據庫資源
    public $connection = null;
    
    //數據庫資源
    public $fileOperation = null;
    
    /**
     * 連接數據庫
     * @param $dbhost
     * @param $username
     * @param $password
     * @param $db_name
     * @param $port
     * @return bool
     */
    function __construct($dbhost='10.3.255.21', $username='off_dbsrt', $password='65c16c8b6', $db_name='ganji_vehicle', $port=3310){
        $this->connection = mysqli_connect($dbhost, $username,  $password, $db_name, $port);
        mysqli_query($this->connection, "set names utf8");
        
        //$this->fileOperation = new FileOperation('chexi_and_chexing');
        $this->fileOperation = new FileOperation('yiche_chexing_map');
    }

    /**
     * 返回上次Insert數據的Id號碼
     */
    public function lastInsertId()
    {
        $id = $this->getOneRecord('SELECT LAST_INSERT_ID() AS insertID');
        if($id !== false && !empty($id) && isset($id['insertID']))
        {
            return $id['insertID'];
        }
        else
        {
            return null;
        }
    }
    
    /**
     * 執行sql[插入,刪除]
     * @param $sql
     * @return bool
     */
    function query($sql, $fun) {
        if (mysqli_query($this->connection, $sql)) {
            echo "MySQL query is ok! fun:".$fun." \n";
            return $this->lastInsertId();
        }else{
            $this->fileOperation->writeToTxt($sql." \n");
            $this->fileOperation->writeToTxt("MySQL query is error! fun:".$fun." \n");
            echo "==============================".$sql." \n";
            echo "==============================MySQL query is error! fun:".$fun." \n";
        }
    }

    function update_query($sql) {
        //用sql 增加新的數據
        $result = mysqli_query($this->connection, $sql);
        if(!$result){
            echo "MySQL update_query is error! \n";
        }
    }
    
    /**
     * 查詢多條數據
     * @param $sql
     * @return bool
     */
    function getAllRecord($sql='') {

        if ($result = mysqli_query($this->connection, $sql))
        {
            $res = array();
            while($row = mysqli_fetch_assoc($result))
            {
                $res[] = $row;
            }
            mysqli_free_result($result);
            return $res;
        } else {
            echo "MySQL getAllRecord is error! \n";
        }
    }
    
    /**
     * 查詢一條數據
     * @param $sql
     * @return bool
     */
    function getOneRecord($sql='') {
        if($result = mysqli_query($this->connection, $sql))
        {
            $res = mysqli_fetch_assoc($result);
            mysqli_free_result($result);
            return $res;
        } else {
            echo "MySQL getOneRecord is error! \n";
        }
    }
}//class end
   
發佈了31 篇原創文章 · 獲贊 15 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章