[php]mysqli操作流程

風痕影默發表於2015-02-07
<?php

class SqlTools{
    private $con;
    private $trans;
    public function __construct($host, $user, $pswd, $db){
        $this->con = new mysqli($host, $user, $pswd, $db);
        if($this->con->connect_error)
            die("CONNECT ERROR:".$this->con->connect_errno.":".$this->con->connect_error."<br/>");
        $this->con->query("set names utf8");
    }
    /*start transaction*/
    public function start_trans(){
        $this->con->autocommit(false);
        $this->trans = true;
    }
    /*rollback*/
    public function rollback(){
        $this->con->rollback();
    }
    /*add, insert, update and so on*/
    public function execute($sql){
        $exec_bool = $this->con->query($sql);
        if($exec_bool)
            die("EXEC ERROR:".$this->con->errno.":".$this->con->error."<br/>");
        return $this->con->affected_rows;
    }
    /*select*/
    public function &execute_query($sql){
        $res = $this->con->query($sql);
        if(!$res)
            die("QUERY ERROR:".$this->con->errno.":".$this->con->error."<br/>");
        return $res;
    }
    /*free resource*/
    public function close(){
        if($this->trans)
            $this->rollback();
        if($this->con)
            $this->con->close();
    }
}

 

相關文章