:::

6. 從資料庫撈出資料(40分鐘)

一、從資料庫讀取單筆資料

PHP的寫法:

$sql="select cht from `xx_oxford` where `eng`='{$eng}'";
$result=mysql_query($sql) or die(mysql_error());
list($cht)=mysql_fetch_row($result);

XOOPS的寫法:

$sql="select cht from ".$xoopsDB->prefix("oxford")."  where `eng`='{$eng}'";
$result=$xoopsDB->queryF($sql) or redirect_header('index.php', 3, mysql_error());
list($cht)=$xoopsDB->fetchRow($result);

$xoopsTpl->assign('eng',$eng);
$xoopsTpl->assign('cht',$cht);
  1. 因為每個 XOOPS 網站的資料表前置字元都不一樣,故必須用$xoopsDB->prefix("資料表名稱") 的方式來替資料表加上前置字元。
  2. 將 $sql 語法送到資料庫執行,可用 $xoopsDB->query($sql) 或者 $xoopsDB->queryF($sql),後者多用在「更新」、「刪除」等地方。
  3. 利用 $xoopsDB->fetchRow($result) 可將抓到的結果用數字索引陣列方式傳回,通常可搭配 list() 來將傳回資料指定到變數中。
  4. 用 $xoopsDB->fetchArray($result) 則是用文字索引陣列傳回。
  5. 利用「$xoopsTpl->assign('樣板標籤名稱' , $變數值);」可將變數送至樣板。

二、套用至樣板

<{if $eng}>
  <div class="hero-unit">
    <h1><{$eng}></h1>
    <p><{$cht}></p>
  </div>
<{/if}>
  1. 先利用<{if}><{/if}>判斷有無輸入關鍵字
  2. 「class="hero-unit"」是BootStrap用來製作醒目區域的一個樣式
  3. <{$eng}>或<{$cht}>都是利用「$xoopsTpl->assign('樣板標籤名稱' , $變數值);」從PHP傳來的樣板變數。
     

三、從資料庫讀取多筆資料

$other="";
$i=1;
$sql="select eng,cht from ".$xoopsDB->prefix("oxford")."  where `eng` like '{$eng}%'";
$result=$xoopsDB->queryF($sql) or redirect_header('index.php', 3, mysql_error());
while(list($eng,$cht)=$xoopsDB->fetchRow($result)){
  $other[$i]['eng']=$eng;
  $other[$i]['cht']=$cht;
  $i++;
}

$xoopsTpl->assign('other',$other);
  1. 利用 SQL中「like」的語法,搭配萬用字元「%」,可以用來做模糊搜尋。
  2. 「$xoopsDB->fetchRow($result)」一次只會抓回一筆資料,故可以用 while() 迴圈,將所有符合條件的資料全部抓回來
  3. 若要套用至樣板迴圈,必須做成陣列形式:「$陣列名稱[$索引]['樣板標籤']=$變數值」
  4. 最後,一樣利用「$xoopsTpl->assign('樣板標籤名稱' , $變數值);」將陣列送至樣板。

四、套用至樣板迴圈

<ol>
  <{foreach from=$other item=other}>
    <li><a href="index.php?eng=<{$other.eng}>"><{$other.eng}></a> <{$other.cht}></li>
  <{/foreach}>
</ol>
  1. 樣板接收到陣列樣板變數,可以用 <{foreach}><{/foreach}>來拆解之。
  2. 「from=$陣列名稱」,from用來接收陣列變數。
  3. 「item=樣板標籤前置字元」,item用來指定迴圈中,樣板標籤的前置字元
  4. 迴圈中,若要指定某個陣列值,可用<{$樣板標籤前置字元.樣板標籤}> 的方式來呈現。

:::

搜尋

QR Code 區塊

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

書籍目錄

展開 | 闔起

線上使用者

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

會員: 0

訪客: 39

更多…