`
yeyuan
  • 浏览: 227441 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

php操作mysql与sqlite类

阅读更多
来源:http://www.yytweb.com/?s=article-13.html
源博客上的类,有些小问题(表前缀只对mysql进行了处理,sqlite的没有处理),下面的这个是我做过一些处理之后的类,我也测试过了,可以使用。感兴趣的朋友也可以继续扩展下。

<?php
/**
 * 文件描述  PDO数据库操作类
 * =================================================================
 * 作    者  YYT<gyyst@126.com>
 * =================================================================
 */

class db
{
	private $config;

	private $db;

	public $querynum;

	public function mysql($host, $user, $password, $dbname, $tablepre = '', $charset = 'GBK')
	{
		$this->config['type'] = 'mysql';
		$this->config['tablepre'] = $tablepre;
		$this->config['mysql']['host'] = $host;
		$this->config['mysql']['user'] = $user;
		$this->config['mysql']['password'] = $password;
		$this->config['mysql']['dbname'] = $dbname;
		$this->config['mysql']['charset'] = $charset;
	}

	public function sqlite($datafile,$tablepre = '')
	{
		$this->config['type'] = 'sqlite';
		$this->config['sqlite']['file'] = $datafile;
                $this->config['tablepre'] = $tablepre;
	}

	private function connect()
	{
		if (isset($this->db)) {
			return true;
		}
		if ($this->config['type'] == 'mysql') {
			try{
				$this->db = new PDO('mysql:host='.$this->config['mysql']['host'].';dbname='.$this->config['mysql']['dbname'], $this->config['mysql']['user'], $this->config['mysql']['password'], array(PDO::ATTR_PERSISTENT => true));
				$this->db->query('SET NAMES '.$this->config['mysql']['charset']);
			} catch (PDOException $e) {
				exit('数据库连接失败:'.$e->getMessage());
			}
		}
		if ($this->config['type'] == 'sqlite') {
			!file_exists($this->config['sqlite']['file']) && exit('没有找到SQLITE数据库');
			$this->db = new PDO('sqlite:'.$this->config['sqlite']['file']);
		}
		!isset($this->db) && exit('不支持该数据库类型 '.$this->config['type']);
	}

	public function table($table)
	{
		return '`'.$this->config['tablepre'].$table.'`';		
	}

	public function strescape($str)
	{
		if ($this->config['type'] === 'mysql') {
			return !get_magic_quotes_gpc() ? addslashes($str) : $str;
		}
		if ($this->config['type'] === 'sqlite') {
			return str_replace('\'', '\'\'', $str);
		}
		return $str;
	}

	public function format_condition($condition)
	{
		if (is_array($condition)) {
			foreach ($condition as $key => $value) {
				$join[] = $key.' = \''.$this->strescape($value).'\'';
			}
			return ' WHERE '.join(' AND ', $join);
		}
		return $condition ? ' WHERE '.$condition : '';
	}

	private function error()
	{
		if ($this->db->errorCode() != '00000') {
			$error = $this->db->errorInfo();
			exit('SQL语句错误:'.$error['2']);
		}
	}

	public function query($sql)
	{
		$this->connect();
		$result = $this->db->query($sql);
		$this->error();
		$result->setFetchMode(PDO::FETCH_ASSOC);
		$this->querynum++;
		return $result;
	}

	public function exec($sql)
	{
		$this->connect();
		$result = $this->db->exec($sql);
		$this->error();
		$this->querynum++;
		return $result;
	}

	public function lastinsertid()
	{
		return $this->db->lastInsertId();
	}

	public function fetchall($table, $field, $condition = '', $sort = '', $limit = '')
	{
		$condition = $this->format_condition($condition);
		$sort && $sort = ' ORDER BY '.$sort;
		$limit && $limit = ' LIMIT '.$limit;
		$sql = 'SELECT '.$field.' FROM '.$this->table($table).$condition.$sort.$limit;
		return $this->query($sql)->fetchall();
	}

	public function fetch($table, $field, $condition = '', $sort = '')
	{
		$condition = $this->format_condition($condition);
		$sort && $sort = ' ORDER BY '.$sort;
		$sql = 'SELECT '.$field.' FROM '.$this->table($table).$condition.$sort.' LIMIT 1';
		return $this->query($sql)->fetch();
	}

	public function rowcount($table, $condition = '')
	{
		$condition = $this->format_condition($condition);
		$sql = 'SELECT COUNT(*) FROM '.$this->table($table).$condition;
		$result = $this->query($sql)->fetch();
		return $result['COUNT(*)'];
	}

	public function get_fields($table)
	{
		if ($this->config['type'] == 'mysql') {
			$sql = 'DESCRIBE '.$this->table($table);
			$key = 'Field';
		} else if ($this->config['type'] == 'sqlite') {
			$sql = 'PRAGMA table_info('.$this->table($table).')';
			$key = 'name';
		}
		$fields = $this->query($sql)->fetchall();
		foreach ($fields as $value) {
			$result[] = $value[$key];
		}
		return $result;
	}

	public function insert($table, $array)
	{
		if (!is_array($array)) {
			return false;
		}
		foreach ($array as $key => $value) {
			$cols[] = $key;
			$vals[] = '\''.$this->strescape($value).'\'';
		}
		$col = join(',', $cols);
		$val = join(',', $vals);
		$sql = 'INSERT INTO '.$this->table($table).' ('.$col.') VALUES ('.$val.')';
		return $this->exec($sql);
	}

	public function update($table, $array, $condition)
	{
		if (!is_array($array)) {
			return false;
		}
		$condition = $this->format_condition($condition);
		foreach ($array as $key => $value) {
			$vals[] = $key.' = \''.$this->strescape($value).'\'';
		}
		$values = join(',', $vals);
		$sql = 'UPDATE '.$this->table($table).' SET '.$values.$condition;
		return $this->exec($sql);
	}

	public function delete($table, $condition)
	{
		$condition = $this->format_condition($condition);
		$sql = 'DELETE FROM '.$this->table($table).$condition;
		return $this->exec($sql);
	}
}

//例子
$db = new db();
//配置数据库,2选一
//$db->mysql($host, $user, $password, $dbname, '表前缀', 'GBK');
$db->sqlite('d:\Backup\test2.db');

//SQL语句查询
$db->query('SELECT * FROM 表')->fetch();//或者fetchall();

//执行一条无返回结果的SQL语句,如插入数据
$db->exec($sql);

//返回最后插入的数据主键
echo $db->lastinsertid();

/***** 下面的操作如果条件为数组则不需要字符转义 *****/

//查询一条数据
$db->fetch('表', '字段1,字段2', '条件,可用数组,如:array(id => 1)', 'id DESC');

//查询所有数据
$db->fetchall('表', '字段1,字段2', '条件,可用数组', 'id DESC', '显示条数');

//插入一条数据
$db->insert('test', array('username' => 'lxx', 'password' => 'lxx'));

//更新一条数据
$db->update('表', array('字段' => '值', '字段2' => '值'), array('id' => '1 更新ID为1的数据'));

//删除一条数据
$db->delete('test', array('username' => 'lxx'));

  • db.rar (2 KB)
  • 下载次数: 20
分享到:
评论

相关推荐

    Ubuntu安装mysql和sqlite3

    Ubuntu安装mysql和sqlite3,里边详细讲解了安装的过程,一步一步的教你怎么安装mysql及sqlite3

    Android 注册登入 (PHP, MySQL 和 SQLite)

    Android 注册登入 (PHP, MySQL 和 SQLite)

    Adminers MYSQL/SQLite管理工具.rar

    Adminers是一款PHP/Mysql/SQLite可视化管理程序,功能类似于phpMyAdmin,不过要比phpMyAdmin更简洁,而且安装配置超简单,因为Adminers仅仅只有一个PHP文件,但它可支持11种界面语言,只要是PHP4.3 ,MySQL 4.1 以上...

    mysql2sqlite:使用 php、pdo 或 exe 将 mysql 数据库转换为 sqlite 数据库-开源

    将 mysql 数据库转换为 Sqlite 数据库。 包括两个项目:A) 一个 php 脚本 B) 一个基于 python 脚本的 Windows 可执行文件 转换数据、索引和外键约束。 关于 php 脚本:-不需要很多内存-良好的速度 预计在 VDS/VPS 上...

    php-sqlite数据库连接类.zip

    sqlite 数据库连接类就是利用了php 与sqlite进行连接操作;数据库连接,返回数据库连接标识符;是否保持持续连接,1为持续连接,0为非持续连接;从结果集中取得一行作为关联数组;显示mysql教程错误信息。

    留言墙留言板php源码access,mysql,sqlite和不用连接数据库的text,txt

    里面包装多种形式的留言板php源码。可以接数据库的access,mysql,sqlite和不用连接数据库的text,txt 演示地址:http://www.guiqishao.com/liuyan

    美优相册管理系统1.1 php+mysql/sqlite

    * 全面支持Sqlite和Mysql两种数据库引擎 * 支持超大图片上传 * 相册可以设置公开或个人,个人相册登录后才可以看到 * 自动生成各种尺寸图片 * 图片批量管理 * 简单防盗链功能 * 可查看图片EXIF信息 * 图片...

    php操作数据库类库,包括MySQL、MSSQL、Oracle、SQLite

    PHP操作数据库的类,包括MySQL、MSSQL、Oracle、SQLite class Database { }

    readerself, 自承载rss阅读器( php/mysql或者 SQLite ) 阅读器替代.zip

    readerself, 自承载rss阅读器( php/mysql或者 SQLite ) 阅读器替代 需求语言PHP 5.3或者更高版本数据库MySQL 5.1或者更高版本SQLite Web服务器在支持 virtualhost/目录配置的virtualhost/目录配置中启用了Apache或者...

    sqlite3数据库操作示例

    它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比...

    Android,java,php开发最基本的知识,mysql sqlite数据库的增删改查代理,sql语句

    Android,java,php开发最基本的知识,mysql sqlite数据库的增删改查代理,sql语句。 博文介绍:http://blog.csdn.net/qq_21376985/article/details/51818806

    convert-mysql-to-sqlite:使用PHP将MySQL转储文件转换为SQLite3的sql文件

    使用PHP将MySQL转储文件转换为SQLite3的sql文件。 演示版 不要上传重要文件。 如果要这样做,请下载此源代码并在本地PHP环境中运行。 本地使用 请规范以下php.ini指令。 您必须根据此规则设置值。 memory_limit ...

    SQLite软件库,SQLite文件包

    SQLite占用资源非常的低,它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库管理...

    windows关于qt的数据库操作封装类以及用例,c++代码

    windows 关于qt的数据库操作封装类 以及用例: SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它的功能特点有: 1. ACID事务 2. 零配置 – 无需安装和管理配置 3....

    php sqlite 企业站模板

    支持跨站调用标签,需PHP 5.1+ 环境,默认支持多数据库(MySQL 5+ 或 SQLite 3+);支持多种(WYSIWYG)编辑器。灵活的HTML样式模板标签,简单易学易部署;支持检索数据库并以KingCMS标签形式调用!

    羊驼 CMS v3.5 SQLite 版

    它基于 php + mysql 、SQLite 并以 b2core MVC 为底层架构。 可以方便快速的配置出个人、企业网站。 羊驼 SQLite 版本在许多用户的要求下, 羊驼发布了 SQLite 版本。 SQLite 的优势:轻量,低负载,方便管理和备份...

    基于PHP+SQLite的WebOS界面CMS/Blog程序--fcontex

    fcontex是开源的基于PHP+SQLite技术的内容管理系统(CMS),同时支持MySQL数据库,用于快速构建中小型企业网站和个人博客(Blog)。 主要特点: 1、默认使用轻量的SQLite数据库,灵活方便; 2、全新的Web OS后台...

    php+sqlite 通用成绩查询系统 v1.0

    前台访问:http://网址/目录/ (上传直接使用,无需mysql数据库等的支持)然后notepad++打开inc/conn.php查看参数与网页对应关系。然后打开默认自带的数据库对比查询结果,查看对应关系。.db 数据库打开方式:sqlite...

    sqlite3.zip

    SQLite3能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,SQLite3的处理...

Global site tag (gtag.js) - Google Analytics