:::
主內容區域
12-3 關於 $xoopsDB 資料庫物件
一、關於$xoopsDB
- XOOPS用來操作資料庫的物件為
$xoopsDB $xoopsDB已經內建,無須自行實體化,直接用即可。- 若是在
function中要使用$xoopsDB資料庫物件,記得用global $xoopsDB,才能使用。
二、$xoopsDB 常用方法:
- 完整方法可參考:http://api.xoops.org/2.5.9/class-XoopsMySQLDatabaseSafe.html
- 自動加上資料表前置字串
$xoopsDB->prefix('資料表名稱') - 執行SQL語法
$xoopsDB->query($sql); $xoopsDB->queryF($sql); - 取得最後新增的編號
$id = $xoopsDB->getInsertId(); - 取得總資料數
$total = $xoopsDB->getRowsNum($result); - 抓回以數字為索引的資料陣列
$data = $xoopsDB->fetchRow($result);- 得到的結果會像:
$data[0]、$data[1]、$data[2]...這樣的數字索引陣列 - 可搭配
list()來將內容指派到變數中,如:list($sn, $title, $content)= $xoopsDB->fetchRow($result);
- 得到的結果會像:
- 抓回以欄名為索引的資料陣列(初學者或欲將整個陣列送至樣板適合使用)
$data = $xoopsDB->fetchArray($result);- 得到的結果會像:
$data['sn']、$data['title']、$data['content']...以欄位名稱為索引的
- 得到的結果會像:
三、常用SQL語法
- 讀出所有資料(完整 select 語法可參考:https://www.fooish.com/sql/select.html)
$sql = "select * from `" . $xoopsDB->prefix("資料表名") . "`"; $result = $xoopsDB->query($sql) or Utility::web_error($sql, __FILE__, __LINE__); $data_arr = []; while ($data = $xoopsDB->fetchArray($result)) { $data_arr[] = $data; } - 讀出單筆資料(完整 select 語法可參考:https://www.fooish.com/sql/where.html)
$sql = "select * from `" . $xoopsDB->prefix("資料表名") . "` where `主索引` = '{$主索引值}'"; $result = $xoopsDB->query($sql) or Utility::web_error($sql, __FILE__, __LINE__); $data = $xoopsDB->fetchArray($result); 或 list($欄位1, $欄位2, $欄位3, ...) = $xoopsDB->fetchRow($result); - 寫入資料(完整 insert 語法可參考:https://www.fooish.com/sql/insert-into.html)
$sql = "insert into `" . $xoopsDB->prefix("資料表名") . "` (`欄位1`, `欄位2`, `欄位3`, ...) values('{$欄位1值}', '{$欄位2值}', '{$欄位3值}', ...)"; $xoopsDB->queryF($sql) or Utility::web_error($sql, __FILE__, __LINE__); //取得最後新增資料的流水編號 $id = $xoopsDB->getInsertId(); - 更新資料(完整 update 語法可參考:https://www.fooish.com/sql/update.html)
$sql = "update `" . $xoopsDB->prefix("資料表名") . "` set `欄位1` = '{$欄位1值}', `欄位2` = '{$欄位2值}', `欄位3` = '{$欄位3值}' ... where `主索引` = '$主索引值'"; $xoopsDB->queryF($sql) or Utility::web_error($sql, __FILE__, __LINE__); - 刪除資料(完整 delete 語法可參考:https://www.fooish.com/sql/delete-from.html)
$sql = "delete from `" . $xoopsDB->prefix("資料表名") . "` where `主索引` = '{$主索引值}'"; $xoopsDB->queryF($sql) or Utility::web_error($sql, __FILE__, __LINE__);
12-2 $xoopsUser 使用者物件