default:
$op = "opList";
$_SESSION['returnUrl'] = getCurrentUrl();
opList();
break;
```
二、函數
1. 列表會有畫面,所以需global $smarty
2. 剛開始可以用「\*」撈所有欄位,後面再選擇要顯示的欄位即可
3. 排序預設為「小->大」,「desc」為 「大->小」,多欄位排序,只要用「,」隔開即可
4. $result 結果
![](https://www.ugm.com.tw/uploads/tad_book3/image/10602/11/11-2.jpg)
5. 因為不知道有多少記錄,所以用「while」迴圈,取得單筆記錄
break:中斷迴圈,但一次只中斷一層(如果是巢狀迴圈)
continue:跳至下一個循環
6. 再把單筆記錄整理至 $rows」,然後送去樣板
7. $rows
![](https://www.ugm.com.tw/uploads/tad_book3/image/10602/11/11-3.jpg)
![](https://www.ugm.com.tw/uploads/tad_book3/image/10602/11/11-3-1.jpg)
8.
```
###############################
# 商品列表
###############################
function opList(){
global $smarty,$db;
#撈商品資料
$sql = "select *
from `ugm_p_prod`
order by `sort` desc
";//die($sql);
$result = $db->query($sql) or redirect_header("", 3000, $db->error."\n".$sql,true);
#查詢筆數
$count = $result->num_rows;
$rows=[];
while($row = $result->fetch_assoc()){
#過濾資料
$row['sn'] = intval($row['sn']);
$row['kind'] = intval($row['kind']);
$row['title'] = htmlspecialchars($row['title'], ENT_QUOTES);
$row['summary'] = htmlspecialchars($row['summary'], ENT_QUOTES);
//$row['content'] = htmlspecialchars($row['content'], ENT_QUOTES);
$row['price'] = intval($row['price']);
$row['amount'] = intval($row['amount']);
$row['enable'] = intval($row['enable']);
$row['choice'] = intval($row['choice']);
$row['date'] = intval($row['date']);
$row['date'] = date("Y-m-d",$row['date']);//格式化
$row['sort'] = intval($row['sort']);
$row['counter'] = intval($row['counter']);
$row['icon'] = htmlspecialchars($row['icon'], ENT_QUOTES);
$row['img'] = getProdImgPath("prod",$row['sn']);
$rows[] = $row;
}
//print_r($rows);die();
$smarty->assign("rows", $rows);//送至樣板
}
function getProdImgPath($col_name,$col_sn){
global $db;
#撈資料
$sql = "select `file_name`,`sub_dir`
from `ugm_p_files_center`
where `col_name`='{$col_name}' and `col_sn`='{$col_sn}'
";
$result = $db->query($sql) or redirect_header("", 3000, $db->error."\n".$sql,true);
$row = $result->fetch_assoc();
if($row){
$row['file_name'] = htmlspecialchars($row['file_name'], ENT_QUOTES);
$row['sub_dir'] = htmlspecialchars($row['sub_dir'], ENT_QUOTES);
$ImgPath = WEB_URL."/uploads/".$row['sub_dir']."/".$row['file_name'];
}else{
$ImgPath="";
}
return $ImgPath;
}
```
三、樣板
1. <img src="<{$row.img}>" style="width:80px;" class='img-responsive'>
src:圖片位置
style:css 語法
img-responsive:bootstrap 圖片響應
2. smrty foreach
from=$rows item=row key=k
$rows:從程式端送來的變數,一筆一筆解出
row:接收解出變數
k:索引值
3.
```
<{if $op == "opList"}>
商品管理 - 列表
縮圖 |
日期 |
標題 |
排序 |
精選 |
啟用 |
新增
|
<{foreach from=$rows item=row key=k}>
|
<{$row.date}> |
<{$row.title}> |
<{$row.sort}> |
<{$row.choice}> |
<{$row.enable}> |
|
<{/foreach}>
<{/if}>
```
四、圖解
![](https://docs.google.com/drawings/d/e/2PACX-1vSiEk5BMCOvWfQo8Uw1gySNgn2JS9CW8PqExw19kT_8yQ99ttaXU6XZqctwrGEiyvcMbzYM3kTwTBdS/pub?w=770&h=820)