在Zend Framework下对数据库的操作一般通过dbAdapter实现其中一种方案如下:
首先在数据库中存在一张表 表名为 test
test 有三个字段:
id int(10) undesigned primary auto-increase
name varchar(10)
description varchar(50)
针对该表,在Zend Framework下,我们应当在modles/DBTable目录下建立一个php文件Test.php,其内容为:
<?php
require_once 'DbTable.php';
class Application_Model_DbTable_Test extends DbTable {
protected $_name = 'test';
protected $fields = array(////fields populated by the UI
'id',
'name',
'description',
);
}
(1)获取db_adapter
$db_test = new Application_Model_DBTable_Test();
$db = $db_test->getAdapter();
(2)查询
在test表中查询id 为1 且 name 为‘canyue’ 的元组
$quote_id = 1;
$quote_name = 'canyue';
$where = $db->quoteInto("id = ?", $quote_id) . $db->quoteInto("name = ?", $ quote_name);
$exist = $db_test ->fetchAll($where);
或
$quote_id = 1;
$quote_name = 'canyue';
$quote = 'id = ' . $quote_id . 'AND' . 'name=' . $quote_name;
$where = $db->quoteInto($quote);
$exist = $db_test ->fetchAll($where);
(3)插入
在test表中插入 name 为 ‘canyue2’, description为'good boy''的元组
$insert['name'] = 'canyue2';
$insert['description'] = 'good boy';
$id = $db_test->insert($insert);
因为设置id字段为自增,所以在插入时id可以不设定此处,$id接受insert()方法返回值,也就是新插入元组的id
(4)更新
将test表中id=1的元组更改为name=‘canyue3’ description=‘good good boy’;
$change['name'] = 'canyue3';
$change['description'] = 'good good boy';
$change_id = 1;
$where = $db->quoteInto("id = ?", $change_id);
$db_test->update($change,$where);
另一种方案等待更新咩--