实现一个简单的php操作SQLite的类

来源:互联网 发布:sql server left join 编辑:程序博客网 时间:2024/05/24 22:44

首先需要安装给php安装sqlite扩展,在php.ini配置文件中添加库的引用依赖,操作类的实现代码如下

<?php/** * @author pengjing * @copyright 2012 */class EasySQLite{    /**     * database object     */    private $conn;    /**     * error information     */    private $error;        /**     * EasySQLite::__construct()     *      * @return     */    function __construct($dbname)    {        $this->conn = $this->connect($dbname);    }    /**     * EasySQLite::__destruct()     *      * @return     */    function __destruct()    {        if($this->conn){            sqlite_close($this->conn);        }    }        /**     * EasySQLite::query()     *      * @param mixed $sql     * @return     */    public function query( $sql )    {        $data = Array();        $i = 0;                $result = sqlite_query($this->conn, $sql, SQLITE_ASSOC, $err_msg);                if($result == false){                $this->error = "SQL error: " . $err_msg;                return NULL;        }        else{                   while($arr = sqlite_fetch_array($result, SQLITE_ASSOC))                {                               $data[$i++] = $arr;                }        }        if(count($data) > 0){            return $data;        }        else{            return sqlite_changes($this->conn);        }    }        /**     * EasySQLite::connect()     *      * @param bool $is_master     * @return     */    private function connect($dbname)    {        $conn = sqlite_open($dbname, 0666, $sqliteerror);        if( !$conn )        {            $this->error = $sqliteerror;            return NULL;        }        return $conn;    }        /**     * EasySQLite::error()     *      * @return     */    public function error(){        return $this->error;    }}?>

使用方法如下:

<?php        require_once("sqlite.php");        $db = new EasySQLite("1.db");        print_r($db->query("delete from user where username = 'ciaos'"));        // rows affected        print_r($db->query("insert into user values('ciaos','pwd')"));        // rows affected        print_r($db->query("update user set username='ciaos2' where username='ciaos'"));        // rows affected        print_r($db->query('select * from user'));        // results array?>
其中插入删除与更新操作均是返回影响的行数,select操作返回结果数组