重新封装的PHPLib DB类 (推荐简单项目使用本类库)
为了便于自己的开发,但是又不想使用ADODB、PEAR::DB这样的庞然大物,就在PHPLib DB类的基础上、参考PEAR::DB类,封装了自己的DB类,简单好使,非常方便。目前只针对MySQL有效,没什么技术含量,姑且为参考。
使用本类库只是需要把下面代码保存为database.inc.php或者database.class.php,在自己需要的地方include进来,然后实例化对象,然后调用连接方法,最后在执行操作。
[ 连接数据库 ]
//包含数据库处理类文件
include_once("database.inc.php");
//本地数据库配置
define("DB_HOST", "localhost"); //数据库服务器
define("DB_USER_NAME", "root"); //数据库用户名
define("DB_USER_PASS", ""); //密码
define("DB_DATABASE", "test"); //数据库
//连接本地数据库
$db = new DB_Sql();
$db->connect(DB_DATABASE, DB_HOST, DB_USER_NAME, DB_USER_PASS);
[ 使用方法 ]
//获取所有记录
$sql = "SELECT * FROM table1";
$all_record = $db->get_all($sql);
//获取一条
$sql = "SELECT * FROM table1 WHERE id = '1'";
$one_row = $db->get_one($sql);
//分页查询,提取20条记录
$sql = "SELECT * FROM table1";
$page_record = $db->limit_query($sql, $start=0, $offset=20, $order="ORDER BY id DESC");
//提取指定数目的记录
$sql = "SELECT * FROM table1";
$limit_record = $db->get_limit($sql);
//统计记录数,统计所有类型为学生的
$count = $db->count("table1", "id", "type = 'student'");
//插入一条记录
$info_array = array(
"name" => "heiyeluren",
"type" => "student",
"age" => "22",
"gender" => "boy"
);
$db->insert("table1", $info_array);
//更新一条记录
$info_array = array(
"name" => "heiyeluren",
"type" => "teacher",
"age" => "22",
"gender" => "boy"
);
$db->update("table1", $info_array, "name = 'heiyeluren'");
//删除记录
$db->delete("table1", "name = 'heiyeluren'");
//执行一条无结果集的SQL
$db->execute("DELETE FROM table1 WHERE name = 'heiyeluren'");
[ 类库代码 ]
| <?php class DB_Sql /* public: configuration parameters */ /* public: result array and current row number */ /* public: current error number and error text */ /* public: this is an api revision, not a CVS revision. */ /* private: link and query handles */ var $locked = false; ## set to true while we have a lock /* public: constructor */ function query_id() { /* public: connection management */ if ("" == $Host) if ("" == $User) if ("" == $Password) if (!@mysql_select_db($Database,$this->Link_ID)) { /* public: discard the query result */ /* public: perform a query */ if (!$this->connect()) { # New query, discard previous result. if ($this->Debug) $this->Query_ID = @mysql_query($Query_String,$this->Link_ID); # Will return nada if it fails. That's fine.
本文关键:重新封装的PHPLib DB类(推荐简单项目使用本类库)
|