使用Zend_Db_Table操作数据库发布时间:2012-11-08 10:24
前两天公司新系统进行了升级,加班也就在所难免,之前打算进行的Zendframework教程也拖延了好几天,在这里说一声抱歉。今天我就来给大家介绍一下Zendframework中的数据库操作Zend_Db_table的使用。 数据库链接首先我们需要链接好数据库。在你阅读完ZendFramework框架之MVC(多模块)环境搭建,成功运行了Zendframework的MVC环境后,应该已经链接好了数据库。但是一定要记住修改application.ini中的数据库链接信息。 查询操作我们需要定义一个model类,使其继承Zend_Db_Table,然后使用$this->_db->select()方法获取select对象,进而进行查询操作,如下: class article extends Zend_Db_Table{ function getListByTime($order, $sortid) { $select = $this->_db->select(); $select->from($this->_name, array('id', 'title')) ->where('sortid != ?', $sortid) ->order($order . ' desc') ->limit(10); $result = $this->_db->fetchAll($select); return $result; } //内容页方法 function getContentById($id) { $select = $this->_db->select(); $select->from($this->_name, array('intro', 'title', 'dateline', 'source', 'author', 'hit', 'id', 'type', 'keywords', 'description', 'sortid', 'is_tutorial')) ->joinLeft('infocontent', 'infocontent.infoid = '.$this->_name.'.id', array('content')) ->where($this->_name.'.id = ?', $id); $result = $this->_db->fetchRow($select); return $result; } } 大家可以看到select对象的查询方法十分易记,这里提示一下:fetchRow()返回符合条件的第一条记录;fetchAll()返回的是符合条件的所有记录。 更新操作要修改表中的任意行数据,我们可以设定一个列名:数据的关联数组作为参数,调 用update()方法,同是通过一个where条件从句来决定需要改变的行.该方法将会 修改表中数据并返回被修改的行数 //更新表中所有数据 public function updateData() { $where = array(); $count = $this->_db->update($this->_name, array('dateline' => time()), $where); return $count; } 添加操作要在表中插入一行新数据,只需要将列名:数据的关联数组作为参数,调用insert()方法即可.(zend framework)会自动对数据进行加引号处理, 并返回插入数据的条数。 public function addData() { $count = $this->_db->insert($this->_name, array('title' => '我的测试')); return $count; } 删除操作要删除表中的数据,我们可以调用delete()方法,同时通过一个where条件 分句来决定需要删除的行.该方法将会返回被删除的行数. public function delData() { $where = $this->_db->quoteInto('title = ?', '我的测试'); $count = $this->_db->delete($this->_name, $where); return $count; } 在我demo示例中,你需要先讲数据库信息配置好,然后只要访问 localhost/zendframwork/default/index/index localhost/zendframwork/default/index/update localhost/zendframwork/default/index/add localhost/zendframwork/default/index/del 就可以查看操作后的结果。 本文来源:http://www./php/zendframework/zend-db-table-operate-examples.shtml |
|