
日期:2006-09-28 作者:喜腾小二 来源:PHPChina
一、
DBQuery对象
现在,我们的DBQuery对象简单地模仿一个存储过程—一旦被执行,即返回一个必须进行保存的结果资源;并且如果你想使用该结果集上的函数(例如num_rows()或fetch_row())的话,你必须传递MySqlDB对象。那么,如果由DBQuery对象来实现MySqlDB对象(其设计目的是对一个执行查询的结果进行操作)实现的函数,效果如何呢?让我们继续使用上一篇示例中的代码;并且让我们假定,现在由DBQuery对象管理我们的结果资源。DBQuery类的源码如列表1所示。
列表1.使用DBQuery类。
| require 'mysql_db.php'; require_once 'query.php'; $db = new MySqlDb; $db->connect('host', 'username', 'pass'); $db->query('use content_management_system'); $query = new DBQuery($db); $query->prepare('SELECT fname,sname FROM users WHERE username=:1S AND pword=:2S AND expire_time<:3I'); try { if($query->execute("visualad", "apron", time()))->num_rows() == 1) { echo('Correct Credentials'); } else { echo('Incorrect Credentials / Session Expired'); } } catch (QueryException $e) { echo('Error executing query: ' . $e); } |
| class DBQuery { ..... public function fetch_array() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_array($this->result); } public function fetch_row() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_row($this->result); } public function fetch_assoc() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_assoc($this->result); } public function fetch_object() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->fetch_object($this->result); } public function num_rows() { if (! is_resource($this->result)) { throw new Exception('Query not executed.'); } return $this->db->num_rows($this->result); } } |
| public function __construct(DB $db) { $this->db = $db; } |