zend framework 中使用dbadapter操作數據庫的幾種方法(持續更新)

在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);

另一種方案等待更新咩--


發佈了38 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章