取得 Zend_Db_Adapter 物件的方法很簡單:
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'localhost',
'username' => 'user',
'password' => 'pass',
'dbname' => 'db'
));quote()
會先對字串做 escape 後,再加上前後的引號。回傳值就可以直接代入 SQL statement 裡了
$name = $db->quote("O'Reilly");
// 'O\'Reilly'
$sql = $db->query("SELECT * FROM table WHERE name = " . $name);quoteInto()
$sql = $db->quoteInto("SELECT * FROM table WHERE name = ?", "O'Reilly");quoteIdentifier()
$tableName = $db->quoteIdentifier("table");
$sql = "SELECT * FROM $tableName";
echo $sql;
// SELECT * FROM `table`
Insert
資料庫 schema 略。
$data = array(
'name' => 'test',
'date' => new Zend_Db_Expr('Now()') // 如果想用資料庫內建函式時,可以用 Zend_Db_Expr 類別
);
$db->insert($table, $data);
// 取得 Generated ID
$id = $db->lastInsertId();Update
$data = array(
'name' => 'test',
'date' => new Zend_Db_Expr('Now()')
);
$where[] = 'id = 1';
// 這樣也可以
// $where['id = ?'] = 1;
// 或是直接傳字串
// $where = 'id = 1';
$n = $db->update($table, $data, $where);Delete
$n = $db->delete($table, 'id = 1');
// $n 代表被刪了幾筆
Transaction
try {
// 現在開始一個交易
$db->beginTransaction();
// 執行動作
$db->query("...");
$db->query("...");
$db->query("...");
// 提交,若有錯誤,會拋出例外
$db->commit();
} catch (Exception $e) {
// 把 db 狀態復原,然後顯示訊息
$db->rollBack();
echo $e->getMessage();
}Column Descriptions
此 function 執行結果會跟 Zend_Db_Table_Abstract 所定義的 protected $_cols; 有關
abstract public function describeTable($tableName, $schemaName = null);