:::

2-2-2 關於 $xoopsDB 資料庫物件

您沒有觀看影片的權限

您沒有觀看影片的權限

請先登入,登入後,確認您的權限後,即可觀看影片。

一、關於$xoopsDB

  1. XOOPS用來操作資料庫的物件為 $xoopsDB
  2. $xoopsDB 已經內建,無須自行實體化,直接用即可。
  3. 若是在 function 中要使用 $xoopsDB 資料庫物件,記得用 global $xoopsDB,才能使用。

二、$xoopsDB 常用方法:

  1. 完整方法可參考:http://api.xoops.org/2.5.9/class-XoopsMySQLDatabaseSafe.html
  2. 自動加上資料表前置字串
    $xoopsDB->prefix('資料表名稱')

     

  3. 執行SQL語法
    $xoopsDB->query($sql);
    $xoopsDB->queryF($sql);

     

  4. 取得最後新增的編號
    $id = $xoopsDB->getInsertId();

     

  5. 取得總資料數
    $total = $xoopsDB->getRowsNum($result);

     

  6. 抓回以數字為索引的資料陣列
    $data = $xoopsDB->fetchRow($result);
    • 得到的結果會像:$data[0]$data[1]$data[2]...這樣的數字索引陣列
    • 可搭配 list() 來將內容指派到變數中,如:
      list($sn, $title, $content)= $xoopsDB->fetchRow($result);

       

  7. 抓回以欄名為索引的資料陣列(初學者或欲將整個陣列送至樣板適合使用)
    $data = $xoopsDB->fetchArray($result);
    • 得到的結果會像:$data['sn']$data['title']$data['content']...以欄位名稱為索引的

三、常用SQL語法

  1. 讀出所有資料(完整 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;
    }

     

  2. 讀出單筆資料(完整 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);

     

  3. 寫入資料(完整 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();

     

  4. 更新資料(完整 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__);

     

  5. 刪除資料(完整 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__);

     


:::

搜尋

QR Code 區塊

https%3A%2F%2Fwww.tad0616.net%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D48%26tbdsn%3D1707

書籍目錄

展開 | 闔起

線上使用者

190人線上 (14人在瀏覽線上書籍)

會員: 0

訪客: 190

更多…