封装php连接mysqli类 封装增删改

来源:互联网 发布:魔兽争霸 知乎 编辑:程序博客网 时间:2024/06/05 02:19
<?phpclass DbMysqli{    private $error = '';    private $errno = 0;    private $port;    private $host;    private $username;    private $password;    private $dbname;    private $charset;    private $db;    /**     * 构造函数     * @author aaron     * @return void      */    function __construct()    {        $this->port = 3306;        $this->host = '127.0.0.1';        $this->username = 'name';        $this->password = 'pwd';        $this->dbname =  'dbname';        $this->charset = 'UTF8';                $db = mysqli_connect($this->host, $this->username, $this->password, $this->dbname,$this->port);        if(!$db){            $this->error = mysqli_connect_error();            $this->errno = mysqli_connect_errno();            return FALSE;        }        mysqli_set_charset($db, $this->charset);        //        $db = mysqli_init();//        mysqli_options($db, MYSQLI_OPT_CONNECT_TIMEOUT, 5);  // 5s 超时//        if(!mysqli_real_connect($db, $this->host, $this->username, $this->password, $this->dbname, $this->port)){//            $this->error = mysqli_connect_error();//            $this->errno = mysqli_connect_errno();//            return FALSE;//        }//        mysqli_set_charset($db,$this->charset);                $this->db = $db;    }            /**     * 数据库连接     * @author aaron     */    private function connect()    {        return $this->db;    }        /**     * 运行Sql语句,不返回结果集     * @author eric     * @param string $sql      * @return mysqli_result|bool     */    public function runSql($sql)    {        $dbconnect = $this->connect();        if ($dbconnect === false) {            return FALSE;        }        // 成功:TRUE 失败:FALSE        $res = mysqli_query($dbconnect,$sql);                // 保存错误        $this->save_error($dbconnect);                return $res;    }        /**     * 获取受影响的行数     * @author aaron     * @param string $sql      * @return int     */    public function affectedRows()    {        $dbconnect = $this->connect();        if ($dbconnect === false) {            return FALSE;        }        $res = mysqli_affected_rows($dbconnect);        // 保存错误        $this->save_error($dbconnect);                return $res;    }         /**     * 运行Sql,以多维数组方式返回结果集     * @author aaron     * @param string $sql      * @return array 成功返回数组,失败时返回false     */    public function getData($sql)    {        // 返回数组        $data = Array();        // 初始化连接        $dbconnect = $this->connect();        if($dbconnect === false){            return FALSE;        }        // 执行sql语句 返回mysqli_result对象        $result = mysqli_query($dbconnect,$sql);        $this->save_error($dbconnect);        if(is_bool($result)){            return $result;        }else{            while($array = mysqli_fetch_array($result, MYSQL_ASSOC)){                $data[] = $array;            }        }        // 关闭 mysqli_result        mysqli_free_result($result);          if(count($data)>0){            return $data;        }else{            return NULL;           }    }                 /**     * 运行Sql,以数组方式返回结果集第一条记录     * @author aaron     * @param string $sql      * @return array 成功返回数组,失败时返回false     */    public function getLine($sql)    {        $data = $this->getData($sql);        if ($data) {            return @reset($data);        } else {            return FALSE;        }    }     /**     * 运行Sql,返回结果集第一条记录的第一个字段值     * @author aaron     * @param string $sql      * @return mixxed 成功时返回一个值,失败时返回false     */    public function getVar( $sql )    {        $data = $this->getLine($sql);        if ($data) {            return $data[@reset(@array_keys($data))];        } else {            return FALSE;        }    }             /**     * 获取新增的id     * @author aaron     * @return int 成功返回last_id,失败时返回false     */    public function lastId()    {        $id = mysqli_insert_id($this->connect());        return $id;    }    /**     * 关闭数据库连接     * @author aaron     * @return bool     */    public function closeDb()    {        @mysqli_close($this->connect());    }            public function errno()    {        return $this->errno;    }    public function errmsg()    {        return $this->error;    }    private function save_error($dbconnect)    {        $this->errno = mysqli_errno($dbconnect);        $this->error = mysqli_error($dbconnect);    }}?>


继承上面的类,继续封装 增删改的操作:

<?phprequire_once 'db_mysqli.php';/** * 新增 * @author aaron * @param object  $db           数据库连接 * @param string  $table_name   表名 * @param array   $params       array('列名'=》'value') * @param bool    $boo          默认false返回操作是否成功 true返回新增ID  * @return $boo=true 返回新增ID  $boo=false 返回新增是否成功 */function db_insert($db, $table_name, $params, $boo=FALSE){    // 列名    $fileds = array();    // 值    $values = array();    foreach ($params as $key => $value) {        $fileds[] = "`".$key."`";        $values[] = "'".$value."'";    }    $str_fileds = implode(',', $fileds);    $str_values = implode(',', $values);    $sql = "insert into `".$table_name."` (".$str_fileds.") values(".$str_values.")";    $result = $db->runSql($sql);        if($boo){        // 获取新增后的ID        $result = $db->lastId();    }    return $result;}/** * 修改 * @author aaron * @param object    $db             数据库连接 * @param string    $table_name     表名 * @param array     $params         array('列名'=》$value) * @param array     $conditions     array('列名'=》$value) * @return bool true 修改成功; false 修改失败 */function db_update($db, $table_name, $params, $conditions){        // 更改的值    $arr_params = array();    foreach ($params as $key => $value) {        if(is_null($value)){            $arr_params[] = "`".$key."` = NULL";        }else{            $arr_params[] = "`".$key."` = '".$value."'";        }    }    // 更改条件    $arr_conditions = array();    foreach ($conditions as $key => $value) {        $arr_conditions[] = "`".$key."` = '".$value."'";    }        $str_fileds = implode(',', $arr_params);    $str_where = implode(' and ', $arr_conditions);    $sql = "update `".$table_name."` set ".$str_fileds." where ".$str_where;    $res = $db->runSql($sql);    return $res;}/** * 删除 * @author aaron * @param object    $db             数据库连接 * @param string    $table_name     表名 * @param array     $conditions     array('列名'=》$value) * @return bool 操作是否成功 */function db_delete($db, $table_name, $conditions){        // 更改条件    $arr_conditions = array();    foreach ($conditions as $key => $value) {        $arr_conditions[] = "`".$key."` = '".$value."'";    }    $str_where = implode(' and ', $arr_conditions);        $sql = "delete from `".$table_name."` where ".$str_where;    $res = $db->runSql($sql);    return $res;}

简单的写了点东西,封装数组的方式 传入 db_insert 、db_update、db_delete,select操作个人还是喜欢直接 select语句来的比较方便、容易操作