pear类的学习之MDB2

1.首先到这个目录中找到Database:http://pear.php.net/packages.php;然后到http://pear.php.net/packages.php?catpid=7&catname=Database,点MD2:http://pear.php.net/package/MDB2

2.按要求安装:http://pear.php.net/package/MDB2/download

3.文档:http://pear.php.net/package/MDB2/docs,每个方法都有例子,这很好!

<pre>
<?php
require_once 'MDB2.php';
//定义$dsn,可以为一数组,也可以为一字符串
$dsn = 'mysql://root:zrp@localhost/test';
$options = array(
    'debug' => 2,
    'result_buffering' => true //这项设为true才能用numRows()方法
);
//连接数据库
$mdb2 =& MDB2::factory($dsn, $options);
if (PEAR::isError($mdb2)) {
    die($mdb2->getMessage());
}
//查询偏移量,注意这个setLimit()中的两个参数,代表的意思正好跟limit 6,2 相反,这里的第一个参数表示查询多少条,第二个是表示从哪里开始(可选),不传第二个参数就表示限制的条数

//$mdb2->setLimit(6, 1);
$res =& $mdb2->query('SELECT * FROM zrp');
//seek($num)表示从哪一行开始显示
//$res->seek(1);
//判断是否有错
if (PEAR::isError($res)) {
    die($res->getMessage());
}
if ($mdb2->getOption('result_buffering')) {
    //返回查询的条数
    echo $res->numRows();
} else {
    echo 'cannot get number of rows in the result set when "result_buffering" is disabled';
}
//获取查询结果,并设置返回的格式:MDB2_FETCHMODE_ORDERED (default) 、MDB2_FETCHMODE_ASSOC、MDB2_FETCHMODE_OBJECT
//可以为 fetchOne(), fetchRow(), fetchCol() and fetchAll()
while (($row = $res->fetchRow(MDB2_FETCHMODE_ASSOC))) {
    // Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED
    echo $row['name'] . "\n";
}

// ...
$name = 'sample item';
$tel = 121;

//添加数据
$query = "INSERT INTO zrp (name, tel) VALUES ('{$name}','{$tel}')";
$res =& $mdb2->exec($query);
//预处理方式插入数据库
$sth = $mdb2->prepare('INSERT INTO zrp(name,tel) VALUES (?, ?)');
$data = array('one', 123456);
$affectedRows = $sth->execute($data);
//习惯性检查语句是否被正确执行
if (PEAR::isError($affectedRows))
{
    die($res->getMessage());
}
$last_id = $mdb2->lastInsertID('zrp', 'id');
if (PEAR::isError($id)) {
    die($id->getMessage());
}
//最新插入的id
echo $last_id;
//修改数据跟删除是一样的,只是sql语句不同而已
//删除数据
$sql="delete from zrp where id=1";
$res=$mdb2->exec($sql);
//关闭连接
$mdb2->disconnect();
?>

 

以下为别人总结的MDB2入门,可以借鉴一下:

PEAR的MDB2使用心得


说使用心得还有点谈不上,刚接触MDB2不到两周。由于服务器升级,新的服务器系统不再安装DB包,PEAR的官方站也明确表示“This package has been superseded, but is still maintained for bugs and security fixes. Use MDB2 instead.”。不得已,研究了一个下午,终于入门了。到现虽然只在两个小项目上小试牛刀,还是有些心得体会的。现在信息扩展之迅速,技术更新之快,倘若你的头脑缓存周期太长,恐怕你费尽心血写出来的东西还没来得及上线下一个版本就出来了。
入题:
"PEAR MDB2 is a merge of the PEAR DB and Metabase php database abstraction layers.”,这是PEAR官网上的一句话,大致是说“PEAR是建立在PHP和数据库之间的一个层”。既然是一个中间层,那么它一定有丰富的扩展功能和灵活的可移植性。就是说你可以把mysql数据库转换为sql server数据库而不需要重写程序,只需要把连接数据库的函数修改一下即可。这点好处我还没有体会到。不过官方文档中还说它有更方便的错误机制处理更安全,Agree.
这里不谈安装,只讲使用。因为打包特别简单,到
http://pear.php.net/package/MDB2/download
下载解压到你的php include path里即可,不要忘记下载MDB2 Driver哦。或者直接使用命令"$ pear install MDB2 $ pear install MDB2#mysql”。
第一步:连接数据库
MDB2提供两种连接方式:DSN&Socket,首选DSN。提供三个连接函数:factory()、connect()、singleton(),分别表示Efficient, Eager, Available连接,就是说factory()是最有效率的连接函数,因为在你只调用factory()的时候它并没有去连接数据库,只有在你发送query请求的时候才会连接;connect()调用时立即连接数据库;而singleton()顾名思义“单独”,为你一个进程只建立一个连接时方便使用,它同样是一个"lazy connecting".
示例函数如下:(其中有一项:$mdb2->setFetchMode(2)是设置数据结果返回的形式为数组)
<?php
require_once
("MDB2.php"); //Connecting primary database; function &open_pdb() { $dsn = array( 'phptype' => "mysql", 'username' => "root", 'password' => "", 'hostspec' => "localhost", 'port' => 3306, 'database' => "test", ); $mdb2 = &MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { exit($mdb2->getMessage()); } $mdb2->setFetchMode(2); return $mdb2; } //Connecting slave database; function &open_sdb() { $dsn = array( 'phptype' => "mysql", 'username' => "root", 'password' => "", 'hostspec' => "localhost", 'port' => 3306, 'database' => "test", ); $mdb2 = &MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { exit($mdb2->getMessage()); } $mdb2->setFetchMode(2); return $mdb2; } //Disconnecting a database function close_db(&$mdb2) { if(is_object($mdb2)) { $mdb2->disconnect(); $mdb2 = ""; } } ?> 第二步:发送请求 MDB2有两种Performing queries方法:query()和exec(),它们分别产生两种结果:成功时返回执行结果和失败时返回MDB2_Error对象。但它们又有不同,query()是请求并取值,它一般用于SELECT,SHOW等,返回符合条件的数据;而exec()是执行的意思,所以它一般用于INSERT、UPDATE或DELETE,返回语句成功执行后所影响的行数。 例如: 假设你已经建立MDB2对象$mdb2 $sql = "SELECT * FROM tableA"; $res = $mdb2->query($sql); //习惯性检查语句是否被正确执行 if (PEAR::isError($res)) { exit($res->getMessage()); } $sql = "INSERT INTO tableB (`id`, `nickname`) VALUES ($id, '$nickname')"; $affected = $mdb2->exec($sql); //习惯性检查语句是否被正确执行 if (PEAR::isError($affected)) { die($res->getMessage()); } ?> 注意:当你使用$mdb2->query()后得到的并不是数组矩阵,而是$mdb2对象,你需要使用fetchOne(),fetchRow(),fetchCol()或fetchAll()来获得你想要的值,这将在接下来讲到。 第三:引用包含Quoting and escaping MDB2提供两个函数来引用SQL语句里的值,分别是Quoting() and escaping(),这是出于安全性的考虑。 在DB库发展到后期,开发人员推荐使用quoteSmart()或escapeSimple()来代替quote(). "This method has been deprecated. Use quoteSmart() or escapeSimple() instead." 但是在MDB2里,我们需要更多地使用quote(),它有4个参数,quote(要quote的值,值的类型,是否使用quote对值进行处理,是否escape通配符),只有第一个参数是必须的。例如: quote($id, "integer")."," .$mdb2->quote($nickname, "text", true)."," .$mdb2->quote($is_member, "boolean", false).")"; echo $sql; //输出结果形如 //INSERT INTO tableA (`id`, `nickname`, `is_member`) VALUES (2, 'jory', 1) ?> 允许的类型有:text, boolean, integer, decimal, float, time stamp, date, time, clob, blob. 其中clob和blob是两种存储不限制长度的大数据对象格式,clob表示以字符串形式存储,blob表示以二进制的形式存储。它们的区别请查阅相关资料。 这样做对SQL语句的严格要求来减少数据库的安全隐患。用的时候你会发现如果类型为text时,当传入变量值为空时,quote后的SQL语句对应值为null,所以我们在设计数据库结构的时候要注意不能把所有的字段都设为not null,允许为空的字段要设计为null. 第四:取得结果数据 上面说到使用query()函数得到的返回值是MDB2对象而不是我们需要的数据,那怎样获得我们存储的数据内容呢,就需要在请求query()后再去取,四种方法: fetchOne(), fetchRow(), fetchCol() and fetchAll().使用过DB库的朋友们看这些函数是不是很眼熟,对的,它就是获取结果集:取一个,取一行,取一列,取所有(比如一个数组矩阵),配合setFetchMode()方法获取你想要的数据形式。 例如:(由于我已经在前的数据库连接函数内使用了$mdb2->setFetchMode(2),这里的返回结果是字符串索引的数组) query($sql); if (PEAR::isError($res)) { exit($res->getMessage()); } $data = $res->fetchAll(); print_r($data); /* 将打印出如下形式数据 Array ( [0] => Array ( [0] => 1 [1] => jory ) [1] => Array ( [0] => 2 [1] => ziming ) [2] => Array ( [0] => 3 [1] => gong ) ) */ ?> 这样每次取数据都要写两行程序,使用MDB2库并没有减少我们敲击键盘的次数。别急,当然更好的方法能让你一步达成: queryOne(), queryRow(), queryCol() and queryAll(). "All of the fetch methods are also available in a variant that executes a query directly" ex. 建立数据库连接对象$mdb2后 $sql = "SELECT * FROM tableA"; //一步达成 $data = $mdb2->queryAll($sql); //结果显示 print_r($data); ?> 第五:预编译及批量处理Prepare & Execute 很多人都喜欢使用prepare()和execute()方法,而我就不太喜欢。我觉得她功能强大但使用起来过于复杂,但事实是她使用起来也很方便的。我喜欢简约一些的,或许是我还没有跨过那道门槛吧。正在尝试...相信有一天我会和她混熟的。 既然是“预编译+批量处理”,那么你只需要简单的两步就能实现对一堆数据的处理: 第一步,整理你的SQL语句(prepare the statement)。第二步,执行(execute it)。 例如: 已经建立一个数据库连接对象$mdb2 $types = array('integer', 'text', 'text'); $sql = "INSERT INTO tableA VALUES (?, ?, ?)"; $sth = $mdb2->prepare($sql, $types); $data = array(1, 'jory', 'I do'); $affectedRows = $sth->execute($data); ?> OK, MDB2的基本使用就说到这里吧,其它的关于事务处理、扩展模块、API接口等等非三二句话能讲得清楚的,欲深究请查阅手册和相关技术文档。 MDB2的一般使用方法总结 2007-06-19 点击: 1107 MDB2的一般使用方法总结 When I started using MDB2, I found the possibilities quite overwhelming and so I decided to summarize everything you may need to start using it or want as a reference if you already use it and don't want to dig through the manuals for everything.Questions and hints on clarification are appreciated. init a connection require_once 'MDB2.php'; $dsn = 'mysql://user:pass@host/db'; docs - factory $mdb2 =& MDB2::factory(mixed $dsn, [ array $options = false]); if (PEAR::isError($mdb2)) { echo ($mdb2->getMessage()); } querying docs - query //Send a query to the database and return any results $result = $mdb2->query(string $query, [mixed $types = null]); docs - queryAll //Execute the specified query, fetch all the rows of the result set into a two dimensional array and then frees the result set. $result = $mdb2->queryAll(string $query, [ array $types = null], [int $fetchmode = MDB2_FETCHMODE_DEFAULT], [boolean $rekey = false]); //$rekey = if set to true, the $all will have the first column as its first dimension docs - queryRow //Execute the specified query, fetch the values from the first row of the result set into an array and then frees the result set. $result = $mdb2->queryRow($string $query, [string $type = null]); results docs - setresultTypes //Define the list of types to be associated with the columns of a given result set. $types = array ('integer', 'text', 'timestamp'); $result->setResultTypes($types) docs - fetchRow //Fetch and return a row of data $result->fetchRow([int $fetchmode = MDB2_FETCHMODE_DEFAULT], [int $rownum = null]); docs - fetchOne //Fetch single column from the first row from a result set $result->fetchOne([int $colnum = 0]); docs - fetchAll //Fetch and return a column of data (it uses fetchRow for that) $result->fetchAll([int $fetchmode = MDB2_FETCHMODE_DEFAULT], [boolean $rekey = false]); //$rekey = if set to true, the $all will have the first column as its first dimension docs - fetchCol //Fetch and return a column of data (it uses current for that) $result->fetchCol([int $colnum = 0]); docs - getColumnnames //Retrieve the names of columns returned by the DBMS in a query result or from the cache. $result->getColumnNames(); docs - numCols //Count the number of columns returned by the DBMS in a query result. $result->numCols(); docs - numRows //returns the number of rows in a result object $result->numRows(); docs - seek //seek to a specific row in a result set $result->seek($int); docs - nextResult //Move the internal result pointer to the next available result $result->nextResult(); docs - free //Free the internal resources associated with result. $result->free(); fetch modes /* MDB2_FETCHMODE_DEFAULT MDB2_FETCHMODE_ORDERED MDB2_FETCHMODE_ASSOC MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED MDB2_FETCHMODE_OBJECT */ security $mdb2->quote($stuff, $mode); text, integer, boolean, decimal, float, date , time , timestamp, blob misc docs - lastInsertID //returns the autoincrement ID if supported or $id $mdb2->lastInsertID(); $mdb2->nextID();

 

 

 
posted @ 2013-05-05 01:24  不负韶华668  阅读(612)  评论(0编辑  收藏  举报