Joomla! 的資料庫處理從以下的程式碼開始
$db = &JFactory::getDBO();
透過 JFactory 取得 JDatabase 的物件參考進行對資料庫的操作
目前 Joomla! 官方只提供 MySQL & MySQLi 的 dirver 可用,尚未有其他 database 的 driver
安裝 Joomla! 時會指定 table prefix 為 jos_,在程式中撰寫 SQL query 時,可用 #__ 來代替,因此假設 table 的名稱為 jos_myTable,撰寫 query 時可改寫為 #__myTable,JDatabase 物件會自動轉換。
要查詢資料,大概就像以下這樣寫就行了....
$db = &JFactory::getDBO();
if (!$result = $db->setQuery($query))
{
// 例外處理
// 可使用 $table->getError() 取得相關錯誤訊息
}
$result = $db->setQuery($query);
查詢資料之前當然要知道怎麼寫 query 語法囉! 以下幾點必須注意的:
使用範例:
$db = &JFactory::getDBO();
$query = "select text from " . $db->nameQuote("#__poll_data") .
" where " . $db->nameQuote("id") . " < 5";
var_dump($query);
$db->setQuery($query);
var_dump($db->loadResultArray());
結果如下:
string 'select text from `#__poll_data` where `id` < 5' (length=46)
array
0 => string 'Community Sites' (length=15)
1 => string 'Public Brand Sites' (length=18)
2 => string 'eCommerce' (length=9)
3 => string 'Blogs' (length=5)
loadResultArray() 是 select 單一值使用,若是要取得整個 table 結構的完整資料,可使用 loadAssocList(), loadObjectList(), 或是 loadRowList()
詳細說明可以參考官方網站 API 文件
若僅要處理單一 table 的資料,Joomla! 提供了 JTable 供使用,目的在於讓開發者省去自行撰寫資料 insert, update, delete 的 SQL 語法。
以下為使用範例:
建立一個 table,結構如下:
要使用 JTable 必須額外針對此 table 撰寫專用的 class 來對應處理,並假設我們將 class 檔案都放置在 JPATH_ADMINISTRATOR/tables 資料夾下
檔案名稱:mySampleJTable.php
以下為程式內容:
【註】檔案名稱 & class name 需要相符合!
接著用以下的程式碼就可以很簡單的新增資料到 table 中
若要刪除資料,使用以下程式碼:
此外,JTable 還針對常用的欄位(published, hits, ordering, checked_out ... etc)提供了 method 來進行特別處理。
以下用幾段範例說明:
void publish ([array $cid = null], [integer $publish = 1], [integer $user_id = 0])
(資料表中需要有 published 欄位)
void hit ([$oid $oid = null], [$log $log = false])
(資料表中需要有 hits 欄位)
boolean isCheckedOut (integer $with, [integer $against = null])
boolean checkout (integer $who, [mixed $oid = null])
boolean checkin ([mixed $oid = null])
(資料表中需要有 checked_out_time 欄位)