Tuesday, February 15, 2011

ZendFrameworks 的技巧 : Zend_Db

// 直接執行 SQL 語法
// 清空 table 資料
$db->getConnection()->exec('TRUNCATE TABLE `foo_bar`');

// update 的 where 語法 1
$where[] = "reported_by = 'goofy'";
$where[] = "bug_status = 'OPEN'";
$db->update('foo_bar', $update_data, $where);
//  WHERE ("reported_by" = 'goofy') AND ("bug_status" = 'OPEN')

// update 的 where 語法 2
$where['reported_by = ?'] = 'goofy';
$where['bug_status = ?']  = 'OPEN';
$db->update('foo_bar', $update_data, $where);
//  WHERE ("reported_by" = 'goofy') AND ("bug_status" = 'OPEN')

// quote 語法
// quote where statement
$where = $db->quoteInto('mkey = ?', $key);
$db->update('foo_bar', $update_data, $where);

// 取得 insert 後得到的 auto incremental id
$db->insert(...);
$id = $db->lastInsertId();

// 先執行 database 的 transaction, 以避免資料寫入失敗情形的發生
$db->beginTransaction();
try {
  $this->db->insert(...);
  $this->db->update(...);
  // 執行都沒問題後, 進行 database 的 commit
  $this->db->commit();
} catch (Exception $e) {
  // 發生問題時, 執行 database 的 roll back
  $this->db->rollBack();
  // 丟出例外發生的文字
  echo $e->getMessage();
}