一、關於本課程
二、 這學期會學到...
三、 開發工具
只要是自己熟悉的純文字編輯工具都可以。
首推sublime text,其次為NotePad++,基本上沒有限制,您用得習慣即可。
四、 開發環境
五、申請免費虛擬主機
六、FB:https://www.facebook.com/groups/968303493248601/
七、學員網站
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap 基礎範本 Template</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="js/bootstrap.min.js"></script> </head> <body> <h1>哈囉, 世界!</h1> </body> </html>
<div class="container"> ... </div>.container-fluid 用於 100% 寬度的容器,橫跨可視區域的全部寬度。
<div class="container-fluid"> ... </div>
<div class="row"> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> </div> <div class="row"> <div class="col-md-8">.col-md-8</div> <div class="col-md-4">.col-md-4</div> </div> <div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> </div> <div class="row"> <div class="col-md-6">.col-md-6</div> <div class="col-md-6">.col-md-6</div> </div>
<p>內容</p>或<div>文字</div>
<img src=”a.jpg”>
<a href=”a.html”>連結</a>
,其中href即為屬性。<IMG>和<img>
一樣,但建議採用小寫。參考網站:https://kkbruce.tw/bs3/Components#navbar
示範網站:https://www.ugm.com.tw/tncomu/nav.html
加入 .navbar-fixed-top
類別可以讓巡覽列固定至頂端,包含 .container
或 .container-fluid
類別讓巡覽列內容置中對齊和左右加入 padding
設置。
<!--導覽列 start--> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">網站名稱</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">首頁</a></li> <li><a href="#">最新消息</a></li> <li><a href="#">關於我們</a></li> <li><a href="#">聯絡我們</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">管理 <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">後台</a></li> <li><a href="#">新聞管理</a></li> <li><a href="#">聯絡我們管理</a></li> <!--分隔線--> <li class="divider"></li> <li><a href="#">關於我們</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav -->
backstretch 一個簡單的jQuery插件,它允許你動態調整大小,幻燈片功能的背景圖像添加到任何頁面或元素
官網:http://srobbin.com/jquery-plugins/backstretch/
示範:https://www.ugm.com.tw/tncomu/backstretch.html
用法:
引入
<script src="js/backstretch/jquery.backstretch.min.js"></script>
設定
<script type="text/javascript"> $(document).ready(function(){ $('.top-content').backstretch([ "img/3.jpg" , "img/2.jpg" , "img/1.jpg" ], {duration: 3000, fade: 750}); }); </script>
一、使用工具,請先安裝
二、BOOTSTRAP框架
<div>內容</div>
常用的屬性有 id(唯一) 、class(多個)
http://www.w3school.com.cn/tags/tag_div.asp
註解
<!-- 註解 -->
一、CSS 参考手册
http://www.w3school.com.cn/cssref/index.asp
二、CSS 套用方式
<div class="container"> <div class="row" style="margin:20px"> <div class="col-md-4" style="background-color: #eee;border: 1px solid #ddd;">.col-md-4</div> <div class="col-md-4" style="background-color: #eee;border: 1px solid #ddd;">.col-md-4</div> <div class="col-md-4" style="background-color: #eee;border: 1px solid #ddd;">.col-md-4</div> </div> <div class="row" style="margin:20px"> <div class="col-md-4" style="background-color: #eee;border: 1px solid #ddd;">.col-md-4</div> <div class="col-md-4" style="background-color: #eee;border: 1px solid #ddd;">.col-md-4</div> <div class="col-md-4" style="background-color: #eee;border: 1px solid #ddd;">.col-md-4</div> </div> </div>
<style type="text/css"> .row { margin:20px; } [class*="col-"] { background-color: #eee; border: 1px solid #ddd; } </style> <div class="container"> <div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> </div> <div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> </div> </div>
<link rel="stylesheet" href="https://www.ugm.com.tw/themes/asia_one_page_3/assets/css/style.css">
匯入套用 (Import)
<STYLE TYPE="text/css"> <!-- @import url(http://https://www.ugm.com.tw/themes/asia_one_page_3/assets/css/style.css); --> </STYLE>
三、CSS 尺寸 (Dimension)
網址:http://tncomu.byethost10.com/nav.html
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>課後練習</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="js/bootstrap.min.js"></script> </head> <body> <!--導覽列 start--> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">育將電腦工作室</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="index.html">首頁</a></li> <li><a href="nav.html">NAV導航</a></li> <li><a href="#">關於我們</a></li> <li><a href="#">聯絡我們</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">管理 <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">後台</a></li> <li><a href="#">新聞管理</a></li> <li><a href="#">聯絡我們管理</a></li> <!--分隔線--> <li class="divider"></li> <li><a href="#">關於我們</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav --> <!--中間區塊--> <div class="container"> <div class="row"> <!--左區塊--> <div class="col-md-3" style="background-color: #93FF93;min-height:500px;"> <h1>左區塊</h1> <a href="http://www.ifreesite.com/color/" target="_blank">色碼表</a> </div> <!--右區塊--> <div class="col-md-9" style="background-color: #9999CC;min-height:500px;"> <h5>右區塊</h5> <p>在標籤中使用 行內套用 (Inline)</p> <code> style="background-color: #93FF93;min-height:500px;" </code> <p>設定背景色 #93FF93 ; 最小高度 500px;</p> <hr> <h5>Bootstrap的 對齊類別</h5> <code> class="text-center" </code> <p> 上面這個是置中<br> <a href="https://kkbruce.tw/bs3/CSS#type-alignment" target="_blank">更多....</a> </p> </div> </div> </div> <!--頁尾--> <footer style="color:#fff; background-color: black;margin-top:20px;"> <div class="container"> <div class="text-center" style="padding:10px;"> <p>育將電腦工作室</p> </div> </div> </footer> </body> </html>
一、關於PHP
二、開發環境
三、開發工具
四、第一個php測試檔(info.php)
<?php phpinfo();
五、註解
請將下列存檔 index.php
PS:注意副檔名為 .php ,請看第26行(與空白架構網頁的差別)
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap 基礎範本 Template</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="js/bootstrap.min.js"></script> </head> <body> <h1><?php echo "哈囉, PHP!" ?></h1> </body> </html>
請參考:http://jimmysu.logdown.com/posts/249495-gmail-smtp-authentication-required
1.將「安全性較低的應用程式存取權限」設為「啟用」
進入此網頁 https://www.google.com/settings/security/lesssecureapps ,設為「啟用」。
如果怕我給的連結是騙人的,您也可以到 Google 帳戶內找到「安全性較低的應用程式存取權限」的設定,是一樣的東西。
這時候再寄看看,通常只要啟用這個,網站的表單就可以正常寄送了。
如果還不行,請再往下看。
2.解除人機驗證鎖定
進入此網頁 https://accounts.google.com/b/0/DisplayUnlockCaptcha 點擊「繼續」。
這時候再寄看看,通常只要啟用這個,網站的表單就可以正常寄送了。
https://www.ugm.com.tw/modules/tad_book3/index.php?op=list_docs&tbsn=11
一、基本注意事項
二、變數與常數以及運算符
資料型態 | 代表意義 |
integer | 整數() |
float | 浮點數 |
boolean | 布林(TRUE或FALSE,不分大小寫) |
string | 字串 |
array | 陣列 |
object | 物件 |
resource | 資源 |
NULL | 空值 |
PHP是一門鬆散類型的語言,因此不需要事先宣告變數的資料類型,PHP會自動將變數轉換為預設的資料類型。
命名規則:
define("常數名稱","常數值");
我們習慣將常數用大寫英文、數字及底線開頭 命名
define("_WEB_URL","https://www.ugm.com.tw/modules/tad_book3/post.php?op=tad_book3_docs_form&tbsn=1&tbdsn=38");
常數以第一次定義為主
運算符號 | 說明 | 例子 | 結果 |
. | 連接字串 |
$a="育將"; $b=$a . "電腦"; |
$b = "育將電腦"; |
<?php echo "<meta charset='utf-8'>"; $name="育將電腦工作室"; $addr="台南市永康區"; echo $name.$addr;
運算符號 | 說明 | 例子 | 結果 |
+ | 加法 |
$a = 6; $a = $a + 4; |
$a = 10; |
- | 減法 |
$a = 6; $a = $a - 4; |
$a = 2; |
* | 乘法 |
$a = 6; $a = $a * 4; |
$a = 24; |
/ | 除法 |
$a = 6; $a = $a / 2; |
$a = 3; |
% | 求餘數 |
$a = 6; $a = $a % 5; |
$a = 1; |
++ | 累加 |
$a = 6; $a++; |
$a = 7; |
-- | 累減 |
$a = 6; $a--; |
$a = 5; |
<?php /* 算數運算符號 */ //指定變數 $a $a = 5; #指定變數 $b $b = 3; //加法 $c = $a+$b ; echo "\$a + \$b=" . $c;
http://tncomu.byethost10.com/4_2.php
運算符號 | 說明 | 例子 | 結果 |
= | 將右邊的值指定給左邊的變數 | $a=6 ; | $a=6 ; |
+= | 左、右相加後,再指定給左邊的變數 |
$a=6 ; $a+=4; |
$a=10 ; |
-= | 左 減 右,再指定給左邊的變數 |
$a=6 ; $a-=4; |
$a = 2; |
*= | 左 乘 右,再指定給左邊的變數 |
$a=6 ; $a*=4; |
$a = 24; |
/= | 左 除 右,再指定給左邊的變數 |
$a=6 ; $a*=3; |
$a = 2; |
‧= | 左 連接 右,再指定給左邊的變數 |
$a = "育將" ; $a .= "電腦"; |
$a = "育將電腦"; |
%= | 左 除 右 之餘數,再指定給左邊的變數 |
$a=3 ; $a %= 2; |
$a = 1; |
比較運算符號
運算符號 | 說明 | 例子 | 結果 |
== | 比較兩邊的數值是否相等 |
$a=5; $b=5; $c=7; |
$a == $b 回傳 true $a == $c 回傳 false |
!= | 比較兩邊的數值是否不相等 |
$a=5; $b=5; $c=7; |
$a != $b 回傳 false $a != $c 回傳 true |
> | 比較左邊的數值是否大於右邊的數值 |
$a=5; $b=5; $c=7; |
$a > $b 回傳 false $a > $c 回傳 false |
< | 比較左邊的數值是否小於右邊的數值 |
$a=5; $b=5; $c=7; |
$a < $b 回傳 false $a < $c 回傳 true |
>= | 比較左邊的數值是否大於等於右邊的數值 |
$a=5; $b=5; $c=7; |
$a >= $b 回傳 true $a >= $c 回傳 false |
<= | 比較左邊的數值是否小於等於右邊的數值 |
$a=5; $b=5; $c=7; |
$a <= $b 回傳 true $a <= $c 回傳 true |
邏輯運算符號
遲算符號 | 說明 | 例子 | 結果 |
&&(and) | 兩邊條件都要成立 | $a=6;$b=4; | ($a > 7 and $b < 10) 傳回 false |
||(or) | 只要其中一邊條件成立 | $a=6;$b=4; | ($a >= 7 or $b < 10) 傳回 true |
!(not) | 反轉 | $a=6;$b=4; | !($a == 6 and $b == 4) 傳回 false |
三、陣列
四、函數
$arr=array( array("品名"=>"蘋果","數量"=>5), array("品名"=>"枊丁","數量"=>3), array("品名"=>"李子","數量"=>9) ); print_r($arr);
顯示:Array ( [0] => Array ( [品名] => 蘋果 [數量] => 5 ) [1] => Array ( [品名] => 枊丁 [數量] => 3 ) [2] => Array ( [品名] => 李子 [數量] => 9 ) )
$arr = "育將電腦工作室"; var_dump($arr);
顯示:string(21) "育將電腦工作室"
function 函數名稱() { 程式碼 return 回傳值; }
一、複習
二、練習
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PHP 第4週</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="js/bootstrap.min.js"></script> </head> <body> <!--導覽列 start--> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php">我的網站名稱</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="index.php">首頁</a></li> <li><a href="about_us.php">關於我們</a></li> <li><a href="contact.php">聯絡我們</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav --> <h1><?php echo "哈囉, 我是index.php" ?></h1> </body> </html>
一、if else ifelse 邏輯判斷語句
if 邏輯判斷語句 | 解釋 |
if(判斷式)(執行程式碼) | 假設判斷式為真,那就執行後面的程式碼 |
if(判斷式){ 執行程式碼1 }else{ 執行程式碼2 } |
假設判斷式為真,那就執行程式碼1 其他的狀況則執行程式碼2 |
if(判斷式1){ 執行程式碼1 }elseif(判斷式2){ 執行程式碼2 }else{ 執行程式碼3 } |
假設判斷式1為真,那就執行程式碼1,若不是則執行判斷式2 假設判斷式1為真,那就執行程式碼1,若不是則執行判斷式2 假設判斷式2為真,那就執行程式碼2 當上面的條件都不真,則執行程式碼3 |
$a=(判斷式)?值1:值2; |
三元判斷式,假設判斷式為真則$a=值1 ,假設判斷式不真則$a=值2 |
二、switch語法
switch($op){ //新增資料 case "op_insert": op_insert($sn); redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_SUCCESS); break; //輸入表格 case "op_form": op_form($sn,$kind); break; //刪除資料 case "op_delete": op_delete($sn); redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_DEL_SUCCESS); break; //預設動作 default: $op="op_list"; op_list($kind); break; }
三、while迴圈
while (條件判斷){
執行的的程式碼
}
5_5.php
<?php echo "<meta charset='utf-8'>"; $i = 1;//設定控制變數 while($i < 10){ //迴圈工作區 echo $i ."<br>"; $i++; }
四、for迴圈
for(設定變數的初始值;設定迴圈停止的條件 ;設定迴圈執行後變數的改變){
執行迴圈的程式碼;
}
5_6.php
<?php echo "<meta charset='utf-8'>"; for($i=1;$i < 10;$i++){ //迴圈工作區 echo $i ."次<br>"; }
continue:跳過迴圈的循環
五、foreach迴圈
foreach(陣列名稱 as 變數名稱){
執行陣列中的程式
}
或
foreach(陣列名稱 as 索引值 => 變數名稱){
執行陣列中的程式
}
<?php echo "<meta charset='utf-8'>"; $a=5; $b=15; echo "\$a={$a}"."<br>"; echo "\$b={$b}"."<br>"; if($b>$a)echo '$b>$a';
<?php echo "<meta charset='utf-8'>"; $a=25; $b=15; echo "\$a={$a}"."<br>"; echo "\$b={$b}"."<br>"; if($b>$a){ echo '$b>$a'; }else{ echo '$a>$b'; }
<?php echo "<meta charset='utf-8'>"; $a=15; $b=15; echo "\$a={$a}"."<br>"; echo "\$b={$b}"."<br>"; if($b>$a){ echo '$b > $a'; }elseif($b<$a){ echo '$b < $a'; }else{ echo '$b = $a'; }
<?php echo "<meta charset='utf-8'>"; $a=15; $b=25; echo "\$a={$a}"."<br>"; echo "\$b={$b}"."<br>"; $msg=($a >= $b)?'$a >= $b':'$a < $b'; echo $msg;
一、5_7.php
<?php echo "<meta charset='utf-8'>"; $nav=array("首頁","聯絡我們","關於我們"); foreach ($nav as $title){ echo $title."<br>"; }
二、5_8.php,您可以將這個帶入 nav.php
<?php echo "<meta charset='utf-8'>\n"; /* <li><a href='index.php'>首頁</a></li> <li><a href='about_us.php'>關於我們</a></li> <li><a href='contact.php'>聯絡我們</a></li> */ $nav=array("index.php" => "首頁" ,"about_us.php" => "關於我們" , "contact.php" => "聯絡我們"); $nav_li=""; foreach ($nav as $href => $title){ $nav_li .= "<li><a href='{$href}'>{$title}</a></li>\n"; } // \n為換行 echo $nav_li;
一、復習
二、習題,如圖,假設您看到前端html語法,請您提出在後台可以保存資料的陣列方法?
請注意圖的紅框部份的規則,在後台設定一個陣列來儲存,然後在前台用foreach函數來撈資料
原本是一個開放原始碼的關聯式資料庫管理系統,原開發者為瑞典的MySQL AB公司,該公司於2008年被昇陽微系統(Sun Microsystems)收購。2009年,甲骨文公司(Oracle)收購昇陽微系統公司,MySQL成為Oracle旗下產品。
MySQL在過去由於效能高、成本低、可靠性好,已經成為最流行的開源資料庫,因此被廣泛地應用在Internet上的中小型網站中。隨著MySQL的不斷成熟,它也逐漸用於更多大規模網站和應用,比如維基百科、Google和Facebook等網站。非常流行的開源軟體組合LAMP中的「M」指的就是MySQL。
但被甲骨文公司收購後,Oracle大幅調漲MySQL商業版的售價,且甲骨文公司不再支援另一個自由軟體專案OpenSolaris的發展,因此導致自由軟體社群們對於Oracle是否還會持續支援MySQL社群版(MySQL之中唯一的免費版本)有所隱憂,因此原先一些使用MySQL的開源軟體逐漸轉向其它的資料庫。例如維基百科已於2013年正式宣布將從MySQL遷移到MariaDB資料庫。
資料型態 | 儲存位元 | 說明 |
---|---|---|
VARCHAR (M) | 1~65535 |
非固定長度字元的資料型態,例如儲存 E-Mail 信箱、聯絡地址 等。 (MySQL資料庫的Varchar類型在5.0.3以下的版本中的最大長度限制為255,其資料範圍可以是0~255) |
CHAR (M) | 1~255 | 固定長度字元的資料型態,例如儲存身份證字號、行動電話號碼 等。 |
TINYTEXT | 255 | 適用於儲存 255 字元以內的資料 |
TEXT | 65535 | 適用於儲存較多字元的資料,例如商品介紹、訪客留言板的內容 等。 |
MEDIUMTEXT | 1677215 | 適用於儲存大容量文字的資料。 |
LONGTEXT | 4294967295 | 適用於儲存超大容量文字的資料。 |
資料型態 | 儲存位元 | 資料範圍 |
TINYINT | 1 byte | signed: -128 ~ 127 unsigned: 0 ~ 255 |
SMALLINT | 2 bytes | signed: -32768 ~ 32767 unsigned: 0 ~ 65535 |
MEDIUMINT | 3 bytes | signed: -8388608 ~ 8388607 unsigned: 0 ~ 16777215 |
INT | 4 bytes | signed: -2147483648 ~ 2147483647 unsigned: 0 ~ 4294967295 |
BIGINT | 8 bytes | signed: -9223372036854775808 ~ 9223372036854775807 unsigned: 0 ~ 1844674407370951615 |
資料型態 | 儲存位元 | 資料範圍 |
DATE | 3 bytes | 1000-01-01 ~ 9999-12-31 |
TIME | 3 bytes | -838:59:59 ~ 838:59:59 |
DATETIME | 8 bytes | 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59 |
adminer:官網 https://www.adminer.org/
執行:
CREATE TABLE prod_kind ( `sn` smallint(5) unsigned NOT NULL auto_increment comment 'sn', `ofsn` smallint(5) unsigned NOT NULL comment '父類別', `kind` varchar(255) NOT NULL default 'nav_home' comment '分類', `title` varchar(255) NOT NULL comment '標題', `sort` smallint(5) unsigned NOT NULL comment '排序', `enable` enum('1','0') NOT NULL default '1' comment '狀態', `url` varchar(255) NOT NULL comment '網址', `target` enum('1','0') NOT NULL default '0' comment '外連', `col_sn` int(10) unsigned NOT NULL comment 'col_sn', `content` text NOT NULL comment '內容', PRIMARY KEY (`sn`) ) ENGINE=MyISAM;
<?php if($_SERVER["SERVER_NAME"] == "localhost" or $_SERVER["SERVER_NAME"] == "127.0.0.1"){ #判斷主機為UniServerZ #MYSQL #資料庫伺服器 $db_host = "localhost"; #資料庫使用者帳號 $db_user = "root"; #資料庫使用者密碼 #$db_password = "12345"; $db_password = "111111"; #資料庫名稱 $db_name = "db2"; }else{ #MYSQL #資料庫伺服器 $db_host = ""; #資料庫使用者帳號 $db_user = ""; #資料庫使用者密碼 $db_password = ""; #資料庫名稱 $db_name = ""; } #PHP 5.2.9以後 $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); if ($mysqli->connect_error) { die('無法連上資料庫 (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } #設定資料庫語系 $mysqli->set_charset("utf8");
$mysqli =
new
mysqli($db_host, $db_user, $db_password, $db_name);
("主機位置","資料庫帳號"," 資料庫密碼");
<?php if($_SERVER["SERVER_NAME"] == "localhost" or $_SERVER["SERVER_NAME"] == "127.0.0.1"){ #判斷主機為UniServerZ #MYSQL #資料庫伺服器 $db_host = "localhost"; #資料庫使用者帳號 $db_user = "root"; #資料庫使用者密碼 #$db_password = "12345"; $db_password = "111111"; #資料庫名稱 $db_name = "db2"; }else{ #MYSQL #資料庫伺服器 $db_host = ""; #資料庫使用者帳號 $db_user = ""; #資料庫使用者密碼 $db_password = ""; #資料庫名稱 $db_name = ""; } #PHP 5.2.9以後 $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); if ($mysqli->connect_error) { die('無法連上資料庫 (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } #設定資料庫語系 $mysqli->set_charset("utf8");
mysql
$sql = "SELECT * FROM `goods` ORDER BY `goods_date` desc"; #送出查詢,回傳查到的資源 $result = mysql_query($sql) or die(mysql_error());//die($sql); #將撈到資料整理成陣列 while ($goods = $result->fetch_assoc()) { $all_goods[] = $goods; }
mysqli
$sql = "SELECT * FROM `goods` ORDER BY `goods_date` desc"; $result = $mysqli->query($sql) or die($mysqli->connect_error); //fetch_all() MYSQLI_ASSOC(陣列), MYSQLI_NUM(序號) , MYSQLI_BOTH(兩者) $all_goods = $result->fetch_all(MYSQLI_ASSOC);
$row=mysql_fetch_array();
$row=mysql_fetch_row();
$row=mysql_fetch_assoc();
一、分析前端語法
二、因為導航是每個網頁都需要且一致的東西,所以把它抽離,而獨立出來成一個變數「$nav」讓每個程式去引入它「require_once("nav.php");」
三、將分析後的資料,手動存放至「資料庫」
<?php /* require_once("nav.php"); */ #查詢語法 /* 選擇所有欄位 從 prod_kind 資料表 在 kind = 'nav_home' 且 enable = '1' 排序 sort 欄位 由小到大 */ $sql="select * from `prod_kind` where `kind`='nav_home' and `enable`='1' order by `sort`"; #送出查詢,回傳查到的資源 $result = mysql_query($sql) or die(mysql_error());//die($sql); #定義 變數 $nav_li $nav_li=""; #開始撈資料 while($row = mysql_fetch_array($result)) { #三元運算 $row['target'] = $row['target'] ?" target='_blank'":""; #串接字串 $nav_li .= "<li><a href='{$row['url']}' {$row['target']}>{$row['title']}</a></li>\n"; } $nav=" <!--導覽列 start--> <nav class='navbar navbar-default' role='navigation'> <div class='container'> <!-- Brand and toggle get grouped for better mobile display --> <div class='navbar-header'> <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1'> <span class='sr-only'>Toggle navigation</span> <span class='icon-bar'></span> <span class='icon-bar'></span> <span class='icon-bar'></span> </button> <a class='navbar-brand' href='index.php'>育將電腦工作室</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class='collapse navbar-collapse' id='bs-example-navbar-collapse-1'> <ul class='nav navbar-nav navbar-right'> <!--帶入變數--> {$nav_li} </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav -->";
CREATE TABLE `ugm_kind` ( `sn` smallint(5) unsigned NOT NULL AUTO_INCREMENT COMMENT 'sn', `ofsn` smallint(5) unsigned NOT NULL COMMENT '父類別', `kind` varchar(255) NOT NULL DEFAULT 'nav_home' COMMENT '分類', `title` varchar(255) NOT NULL COMMENT '標題', `sort` smallint(5) unsigned NOT NULL COMMENT '排序', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', `url` varchar(255) NOT NULL COMMENT '網址', `target` enum('1','0') NOT NULL DEFAULT '0' COMMENT '外連', `col_sn` int(10) unsigned NOT NULL COMMENT 'col_sn', `content` text NOT NULL COMMENT '內容', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `ugm_prod` ( `sn` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'prod_sn', `kind` smallint(5) unsigned NOT NULL COMMENT '分類', `title` varchar(255) NOT NULL COMMENT '名稱', `summary` text NOT NULL COMMENT '摘要', `content` text NOT NULL COMMENT '內容', `price` int(10) unsigned NOT NULL COMMENT '價格', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', `date` int(10) unsigned NOT NULL COMMENT '建立日期', `sort` smallint(5) unsigned NOT NULL COMMENT '排序', `counter` int(10) unsigned NOT NULL COMMENT '人氣', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `ugm_contact` ( `sn` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'sn', `name` varchar(255) NOT NULL COMMENT '姓名', `tel` varchar(255) NOT NULL COMMENT '電話', `email` varchar(255) NOT NULL COMMENT '電子信箱', `contact` text NOT NULL COMMENT '聯絡內容', `date` int(10) unsigned NOT NULL COMMENT '聯絡日期', `ip` varchar(255) NOT NULL COMMENT 'ip', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `ugm_system` ( `sn` smallint(5) unsigned NOT NULL AUTO_INCREMENT COMMENT 'sn', `name` varchar(255) NOT NULL DEFAULT '' COMMENT '表單名稱', `kind` varchar(255) NOT NULL DEFAULT 'system' COMMENT '類別', `title` varchar(255) NOT NULL DEFAULT '' COMMENT '標題', `value` text COMMENT '值', `description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述', `formtype` varchar(255) NOT NULL DEFAULT '' COMMENT '表單型態', `valuetype` varchar(255) NOT NULL DEFAULT '' COMMENT '值的型態', `sort` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '排序', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `ugm_files` ( `sn` smallint(5) unsigned NOT NULL AUTO_INCREMENT COMMENT '檔案流水號', `col_name` varchar(255) NOT NULL DEFAULT '' COMMENT '欄位名稱', `col_sn` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '欄位編號', `sort` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '排序', `kind` enum('img','file') NOT NULL DEFAULT 'img' COMMENT '檔案種類', `file_name` varchar(255) NOT NULL DEFAULT '' COMMENT '檔案名稱', `file_type` varchar(255) NOT NULL DEFAULT '' COMMENT '檔案類型', `file_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '檔案大小', `description` text NOT NULL COMMENT '檔案說明', `counter` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '下載人次', `sub_dir` varchar(255) NOT NULL DEFAULT '' COMMENT '檔案子路徑', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
<img src="http://fakeimg.pl/300/"> <img src="http://fakeimg.pl/250x100/"> <img src="http://fakeimg.pl/250x100/ff0000/"> <img src="http://fakeimg.pl/350x200/ff0000/000"> <img src="http://fakeimg.pl/350x200/ff0000,128/000,255"> <img src="http://fakeimg.pl/350x200/?text=Hello"> <img src="http://fakeimg.pl/350x200/?text=World&font=lobster">
{literal} <script type="text/javascript"> $(document).ready(function(){ $('.top-content').backstretch([ "http://fakeimg.pl/1600x1200/ff0000/" , "http://fakeimg.pl/1600x1200/00ff00/" , "http://fakeimg.pl/1600x1200/0000ff/" ], {duration: 3000, fade: 750}); }); </script> {/literal}
{if $file_name == "index.php"} {else} {/if}
{foreach from=$陣列變數 item=陣列元素名稱 key=陣列索引名稱} {/foreach}
二、安裝
<?php #網站常數、連線資料庫設定 require_once 'config.php'; #引入樣版引擎s require_once 'smarty.php'; #導航 require_once 'nav.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; #程式流程 switch($op){ #---- case "op_test": op_test(); break; #---- case "op_test1": op_test1(); break; //預設動作 default: $op="op_list"; break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); #檔案名稱(含副檔),變數在config.php $smarty->assign("file_name", $file_name); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # op_test ######################################## function op_test() { return; } ######################################## # op_test1 ######################################## function op_test1() { return; }
<?php error_reporting(E_ALL); @ini_set('display_errors', true); // URL Association for SSL and Protocol Compatibility $http = 'http://'; if (!empty($_SERVER['HTTPS'])) { $http = ($_SERVER['HTTPS']=='on') ? 'https://' : 'http://'; } #網站實體路徑 define('WEB_PATH', str_replace("\\","/",dirname(__FILE__))); #網站URL define('WEB_URL', $http.$_SERVER["HTTP_HOST"].str_replace($_SERVER["DOCUMENT_ROOT"],"",WEB_PATH)); #佈景目錄 define('WEB_THEME', "default"); #網站名稱 define('WEB_TITLE', "網站名稱"); #取得檔名 $file_name=basename ($_SERVER['PHP_SELF']);//index.php #MYSQL #資料庫伺服器 $db_host = "localhost"; #資料庫使用者帳號 $db_user = "root"; #資料庫使用者密碼 $db_password = "111111"; #資料庫名稱 $db_name = "tncomu"; #PHP 5.2.9以後 $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); if ($mysqli->connect_error) { die('無法連上資料庫 (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } #設定資料庫語系 $mysqli->set_charset("utf8");
<?php session_start(); error_reporting(E_ALL); @ini_set('display_errors', true); // URL Association for SSL and Protocol Compatibility $http = 'http://'; if (!empty($_SERVER['HTTPS'])) { $http = ($_SERVER['HTTPS']=='on') ? 'https://' : 'http://'; } #網站實體路徑 define('WEB_PATH', str_replace("\\","/",dirname(__FILE__))); #網站URL define('WEB_URL', $http.$_SERVER["HTTP_HOST"].str_replace($_SERVER["DOCUMENT_ROOT"],"",WEB_PATH)); #佈景目錄 define('WEB_THEME', "default"); #網站名稱 define('WEB_TITLE', "網站名稱"); #取得檔名 $file_name=basename ($_SERVER['PHP_SELF']);//index.php if($_SERVER["SERVER_NAME"] == "localhost"){ #判斷主機為UniServerZ #MYSQL #資料庫伺服器 $db_host = "localhost"; #資料庫使用者帳號 $db_user = "root"; #資料庫使用者密碼 $db_password = "111111"; #資料庫名稱 $db_name = "db2"; }else{ #MYSQL #資料庫伺服器 $db_host = ""; #資料庫使用者帳號 $db_user = ""; #資料庫使用者密碼 $db_password = ""; #資料庫名稱 $db_name = ""; } #PHP 5.2.9以後 $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); if ($mysqli->connect_error) { die('無法連上資料庫 (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } #設定資料庫語系 $mysqli->set_charset("utf8");
<?php #引入smarty物件 require_once WEB_PATH.'/class/smarty/Smarty.class.php'; #實體化 $smarty = new Smarty; #設定模板路徑 $smarty->template_dir = WEB_PATH.'/templates/'.WEB_THEME; #設定編譯路徑 $smarty->compile_dir = WEB_PATH.'/templates_c/'; #設定檔路徑 $smarty->config_dir = WEB_PATH.'/configs/'; #設定暫存路徑 $smarty->cache_dir = WEB_PATH.'/cache/'; #設定模板URL $smarty->assign("themeUrl", WEB_URL.'/templates/'.WEB_THEME);
<?php $nav=" <!--導覽列 start--> <nav class='navbar navbar-default' role='navigation' style='margin-bottom:0;'> <div class='container'> <!-- Brand and toggle get grouped for better mobile display --> <div class='navbar-header'> <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1'> <span class='sr-only'>Toggle navigation</span> <span class='icon-bar'></span> <span class='icon-bar'></span> <span class='icon-bar'></span> </button> <a class='navbar-brand' href='index.php'>".WEB_TITLE."</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class='collapse navbar-collapse' id='bs-example-navbar-collapse-1'> <ul class='nav navbar-nav navbar-right'> <li><a href='index.php'>首頁</a></li> <li><a href='about_us.php'>關於我們</a></li> <li><a href='contact.php'>聯絡我們</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav --> "; #將變數送至樣版引擎 $smarty->assign("nav" , $nav);
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{$smarty.const.WEB_TITLE}</title> <!-- Bootstrap --> <link href="{$themeUrl}/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="{$themeUrl}/js/html5shiv.min.js"></script> <script src="{$themeUrl}/js/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用) --> <script src="{$themeUrl}/js/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="{$themeUrl}/js/bootstrap.min.js"></script> {literal} <script type="text/javascript"> </script> {/literal} </head> <body> {$nav} {* 在index.php *} {if $file_name == "index.php"} <script src="{$smarty.const.WEB_URL}/class/backstretch/jquery.backstretch.min.js"></script> {literal} <script type="text/javascript"> $(document).ready(function(){ $('.top-content').backstretch([ "http://fakeimg.pl/1600x1200/ff0000/" , "http://fakeimg.pl/1600x1200/00ff00/" , "http://fakeimg.pl/1600x1200/0000ff/" ], {duration: 3000, fade: 750}); }); </script> {/literal} <style> .top-content{ height:600px; } </style> <div class="top-content"> </div> <div class="container" style="margin-top:40px;"> <div class="row"> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="http://fakeimg.pl/800x600/"> </a> </div> </div> </div> {/if} {* 在contact.php 或 about_us.php *} {if $file_name == "contact.php" or $file_name == "about_us.php"} <div class="container" style="margin-top:40px;"> <div class="row"> <div class="col-md-12 bg-info" style="height:460px;"> </div> </div> </div> {/if} <!--頁尾--> <div class="bg-warning" style="margin-top:20px;"> <div class="container" style="height:40px;line-height:40px;"> <div class="text-center"><a href="{$smarty.const.WEB_URL}">{$smarty.const.WEB_TITLE}</a></div> </div> </div> </body> </html>
在樣版裡,我們可以透過Smarty預先定義好的變數,以存取PHP中的全域變數(SuperGlobals)
Smarty 保留變數 | 等同的PHP變數 |
$smarty.get | $_GET |
$smarty.post | $_POST |
$smarty.request | $_REQUEST |
$smarty.session | $_SESSION |
$smarty.cookies | $_COOKIE |
$smarty.env | $_ENV |
$smarty.server | $_SERVER |
$smarty.const | 利用define函式定義的常數 |
一、更新專案:
二、規劃後台
三、表單
四、實做
五、完整程式碼:https://www.dropbox.com/s/gzfdcytzoqhi8pl/9_20160504_ok_web1.zip?dl=0 (記得 調整 config.php)
if($_SERVER["SERVER_NAME"] == "localhost"){ #判斷主機為UniServerZ #MYSQL #資料庫伺服器 $db_host = "localhost"; #資料庫使用者帳號 $db_user = "root"; #資料庫使用者密碼 $db_password = ""; #資料庫名稱 $db_name = ""; }else{ #MYSQL #資料庫伺服器 $db_host = ""; #資料庫使用者帳號 $db_user = ""; #資料庫使用者密碼 $db_password = ""; #資料庫名稱 $db_name = ""; }
<?php require_once 'head.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; #程式流程 switch($op){ #---- case "op_test": op_test(); break; #---- case "op_test1": op_test1(); break; //預設動作 default: $op="op_list"; break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); #檔案名稱(含副檔),變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # op_test ######################################## function op_test() { return; } ######################################## # op_test1 ######################################## function op_test1() { return; }
<?php session_start(); #這個函數之前不能有輸出 #Session:儲存於伺服器端,不用擔心用戶禁用session的問題,但記錄檔案的負荷由伺服器承擔。 #Cookie:儲存於用戶端,可能有用戶端禁用cookie,但伺服器不需承擔記錄檔案的負荷。
<?php session_start(); $_SESSION['uname'] = true; $_SESSION['aaa'] = "變數值";
<?php session_start(); $_SESSION["uname"] = true; #取得 session 的值,使用 if($_SESSION["uname"]) { echo "我是管理員"; }
<?php session_start(); $_SESSION["uname"] = true; #清除 $_SESSION["uname"] =""; #刪除 unset($_SESSION["uname"] );
<?php session_start();//啟用 $_SESSION,前面不可以有輸出 error_reporting(E_ALL); @ini_set('display_errors', true);//設定所有錯誤都顯示 // URL Association for SSL and Protocol Compatibility $http = 'http://'; if (!empty($_SERVER['HTTPS'])) { $http = ($_SERVER['HTTPS']=='on') ? 'https://' : 'http://'; } #網站實體路徑 define('WEB_PATH', str_replace("\\","/",dirname(__FILE__))); #網站URL define('WEB_URL', $http.$_SERVER["HTTP_HOST"].str_replace($_SERVER["DOCUMENT_ROOT"],"",WEB_PATH)); #佈景目錄 $WEB['theme_name'] = "default"; #網站名稱 $WEB['title'] = "網站名稱"; #程式檔名(含副檔名) $WEB['file_name'] = basename ($_SERVER['PHP_SELF']);//index.php #引入 mysql設定 require_once 'config.php'; #引入樣版引擎s require_once 'smarty.php'; #共用函數 require_once 'function.php'; #導航 require_once 'nav.php';
一、HTML Form 語法
<form action="資料傳送目的地" method="資料傳遞方式"> 表單內容與表單元素 </form>
標準的 HTML 表單是由 <form> 標籤開始,結尾使用 </form> 標籤,兩個標籤之間就是放置表單元素的地方,form 會將網友填完的資料,傳送至 action 所設定的資料傳送目的地,例如傳給一個 PHP 頁面,進行資料的接收,method 是資料傳遞的方式,有 get 與 post 兩種方式。
二、表單元件
三、其他常用的表單元件 HTML 語法及屬性
四、接收表單變數
<?php require_once 'head.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; #程式流程 switch($op){ #---- case "op_test": op_test(); break; #---- case "op_test1": op_test1(); break; //預設動作 default: $op="op_list"; break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); #檔案名稱(含副檔),變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # op_test ######################################## function op_test() { return; } ######################################## # op_test1 ######################################## function op_test1() { return; }
#定義變數, $_SESSION['uname']用來判斷是否登入 $_SESSION['uname']=isset($_SESSION['uname'])?$_SESSION['uname']:"";
在流程控制加上
//預設動作 default: $op="op_list"; if($_SESSION['uname']){ #如果已經登入,則跳轉至後台的首頁 header("location:admin/index.php"); } break;
此時,因為還沒登入,所以程式執行結束,而螢幕是空畫面,接下來做一張表單,資料傳送目的地 admin.php 方法 post
{* admin.php *} {if $WEB.file_name == "admin.php"} <div class="container" style="margin-top:40px;min-height:550px;"> <div class="row"> <div class="col-md-4 col-md-offset-4 bg-success" style="padding:20px;"> <form action="admin.php" method="post"> <div class="form-group"> <label>帳號</label> <input type="text" class="form-control" id="uname" name="uname" placeholder="帳號"> <p class="help-block">請輸入帳號,最多8個字元</p> </div> <div class="form-group"> <label>密碼</label> <input type="password" class="form-control" id="pass" name="pass" placeholder="密碼"> <p class="help-block">請輸入密碼,最多8個字元</p> </div> <!--用來控制程式流程--> <input type="hidden" name="op" value="check_uname"> <button type="submit" class="btn btn-default">送出</button> </form> </div> </div> </div> {/if}
<form action="admin.php" method="post"> 接收表單的程式 admin.php 方法 post
隱藏一個 $_POST['op'] = check_uname
#登入 case "check_uname": $msg = check_uname(); if($msg){ #如果帳號、密碼,驗證ok,則跳轉至,後台首頁 $_SESSION['uname'] = true; header("location:admin/index.php"); exit; } //header("location:index.php"); //exit; //$smarty->assign("msg", "請輸入正確帳號、密碼"); break;
#函數 ######################################## # check_uname ######################################## function check_uname() { #過濾接教變數, 特殊字符轉義 $_POST['uname'] = addslashes($_POST['uname']); $_POST['pass'] = addslashes($_POST['pass']);// if($_POST['uname'] == "admin" and $_POST['pass'] == "admin123456")return true; return; }
登出,請檢查後台的登出連結 「 ../admin.php?op=logout 」
在流程增加 logout => $_SESSION['uname'] = ""; 即可
在前台增加一個隱藏的登入點:編輯樣版
樣板位置:web/templates/default/theme.html
編輯「theme.html」將語法放在 </body> 之前
{* 登入用 *} <div style='position:fixed;top:1px;left:1px;z-index:10000'> <a href="admin.php"> </a> </div >
{* 登入用 *}:smarty 的註解
position:fixed; :固定定位(position: fixed)的元素會相對於瀏覽器視窗來定位,這意味著即便頁面捲動,它還是會固定在相同的位置。
z-index 可以用來設置元素的 Z 方向位置,z-index 數字越大的在越上面,反之則在越下面。
後台要驗證 $_SESSION['uname'],假如不真,則跳回前台頁頁
#沒有登入,則回到前台首頁 if(!$_SESSION['uname'])header("location:../index.php");
一、實做:
上節我們利用$_SESSION,做了「登入」、「登出」的功能,這二個動作都必須「轉向」,但轉向後並沒有訊息告知動作是否成功或失敗,因此有需要製做一個,資訊通知中心。
http://tncomu.byethost10.com/soft/10_20160511_web.zip
一、先從官網將方法整理成一般網頁
<!--引入CSS--> <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.css" />
<!--引入JS--> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.js"></script>
<!--調用插件--> <script type="text/javascript"> $(document).ready(function(){ $.jGrowl('訊息通知中心', { life:3000 , position: 'center', speed: 'slow' }); }); </script>
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery jGrowl</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="js/bootstrap.min.js"></script> </head> <body> <h1>jQuery jGrowl</h1> <!--引入CSS--> <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.css" /> <!--引入JS--> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.js"></script> <!--調用插件--> <script type="text/javascript"> $(document).ready(function(){ $.jGrowl('訊息通知中心', { life:3000 , position: 'center', speed: 'slow' }); }); </script> </body> </html>
function redirect_header($url="", $time = 3000, $message = '已轉向!!') { $_SESSION['redirect']=" $(document).ready(function(){ $.jGrowl('{$message}', { life:{$time} , position: 'center', speed: 'slow' }); }); "; header("location:{$url}"); exit; }
function:將指令、函數組合成一個套件。
可設預設值:$time = 3000 ,3000即是預設值
回傳:利用 return 傳回變數或陣列
這裡利用 $_SESSION['redirect'] ,當這個變數有值,即代表有轉向動作,因此在佈景可以判斷 $_SESSION['redirect'] 是否有值,如果有,則調用插件顯示訊息。
當程式執行 redirect_header(),除了設定 $_SESSION['redirect']外,並執行轉向 header("location:{$url}");
前、後台head.php
$_SESSION['redirect']=isset($_SESSION['redirect'])?$_SESSION['redirect']:""; $smarty->assign("redirect", $_SESSION['redirect']); $_SESSION['redirect']="";
<?php require_once 'head.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; #定義變數, $_SESSION['uname']用來判斷是否登入 $_SESSION['uname']=isset($_SESSION['uname'])?$_SESSION['uname']:""; #程式流程 switch($op){ #登入 case "check_uname": $msg = check_uname(); if($msg){ #如果帳號、密碼,驗證ok,則跳轉至,後台首頁 $_SESSION['uname'] = true; redirect_header("admin/index.php",3000,"您好:歡迎光臨!!<br>目前在後台首頁!!"); //header("location:admin/index.php"); exit; } break; #---- case "logout": $_SESSION['uname'] = ""; redirect_header("index.php",3000,"您已經登出!!"); exit; break; //預設動作 default: $op="op_list"; if($_SESSION['uname']){ #如果已經登入,則跳轉至後台的首頁 redirect_header("admin/index.php",3000,"您好:歡迎光臨!!<br>目前在後台首頁!!"); exit; } break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); #檔案名稱(含副檔),變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # check_uname ######################################## function check_uname() { #過濾接教變數, 特殊字符轉義 $_POST['uname'] = addslashes($_POST['uname']); $_POST['pass'] = addslashes($_POST['pass']);// if($_POST['uname'] == "admin" and $_POST['pass'] == "admin123456")return true; return; } ######################################## # op_test1 ######################################## function op_test1() { return; }
{if $redirect} <link rel="stylesheet" type="text/css" href="{$smarty.const.WEB_URL}/class/jgrowl/jquery.jgrowl.min.css" /> <script src="{$smarty.const.WEB_URL}/class/jgrowl/jquery.jgrowl.min.js"></script> <script type='text/javascript'> {$redirect} </script> {/if}
CREATE TABLE `show_kind` ( `sn` smallint(5) unsigned NOT NULL AUTO_INCREMENT COMMENT 'sn', `ofsn` smallint(5) unsigned NOT NULL COMMENT '父類別', `kind` varchar(255) NOT NULL DEFAULT 'nav_home' COMMENT '分類', `title` varchar(255) NOT NULL COMMENT '標題', `sort` smallint(5) unsigned NOT NULL COMMENT '排序', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', `url` varchar(255) NOT NULL COMMENT '網址', `target` enum('0','1') NOT NULL DEFAULT '0' COMMENT '外連', `col_sn` int(10) unsigned NOT NULL COMMENT 'col_sn', `content` text NOT NULL COMMENT '內容', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
<?php $nav=" <!--導覽列 start--> <nav class='navbar navbar-default' role='navigation' style='margin-bottom:0;'> <div class='container'> <!-- Brand and toggle get grouped for better mobile display --> <div class='navbar-header'> <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1'> <span class='sr-only'>Toggle navigation</span> <span class='icon-bar'></span> <span class='icon-bar'></span> <span class='icon-bar'></span> </button> <a class='navbar-brand' href='../index.php'>{$WEB['title']}</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class='collapse navbar-collapse' id='bs-example-navbar-collapse-1'> <ul class='nav navbar-nav navbar-right'> <li><a href='index.php'>後台首頁</a></li> <li><a href='nav_m.php'>選單管理</a></li> <li><a href='../admin.php?op=logout'>登出</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav --> "; #將變數送至樣版引擎 $smarty->assign("nav" , $nav);
<?php require_once 'head.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; $sn = isset($_REQUEST['sn'])?intval($_REQUEST['sn']):""; #程式流程 switch($op){ #新增記錄 case "op_insert": op_insert(); redirect_header("index.php",3000,"新增記錄成功!!"); exit; break; #更新記錄 case "op_update": op_update($sn); redirect_header("index.php",3000,"更新記錄成功!!"); exit; break; #刪除記錄 case "op_delete": op_delete($sn); redirect_header("index.php",3000,"刪除記錄成功!!"); exit; break; #表單 case "op_form": op_form($sn); break; #顯示單筆 case "op_show": op_show($sn); break; #列表 default: $op="op_list"; op_list(); break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); /* $WEB['theme_name'] = "admin"; WEB['title'] = "網站名稱"; $WEB['file_name'] = basename ($_SERVER['PHP_SELF']); */ #變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # op_insert ######################################## function op_insert() { global $mysqli; return; } ######################################## # op_update ######################################## function op_update($sn="") { global $mysqli; return; } ######################################## # op_delete ######################################## function op_delete($sn="") { global $mysqli; return; } ######################################## # op_form ######################################## function op_form($sn="") { global $mysqli,$smarty; return; } ######################################## # op_show ######################################## function op_show($sn="") { global $mysqli,$smarty; return; } ######################################## # op_list ######################################## function op_list() { global $mysqli,$smarty; return; }
一、分析所需表單欄位:
標題 title (text)、網址 url (text)、是否外連 target (radio)、是否啟用 enable (radio)、排序 sort(text)
分類 kind="nav_home"
二、流程控制:
收到 op_form 進入表單(新增、編輯) => 送出一個 op_insert、op_update(寫入資料庫、更新資料庫)
三、函數:
op_form($sn)
######################################## # 表單 ######################################## function op_form($sn="") { global $mysqli,$smarty; #抓取預設值 if($sn) { #編輯 $DBV['op'] = "op_update"; $DBV['form_title'] = "編輯選單"; }else { #新增 $DBV=array(); $DBV['op'] = "op_insert"; $DBV['form_title'] = "新增選單"; } //預設值設定 //標題 title (text)、網址 url (text)、是否外連 target (radio)、是否啟用 enable (radio)、排序 sort(text) $DBV['sn'] = (isset($DBV['sn'])) ? $DBV['sn'] : ""; $DBV['title'] = (isset($DBV['title'])) ? $DBV['title'] : ""; $DBV['enable'] = (isset($DBV['enable'])) ? $DBV['enable'] : "1"; $DBV['target'] = (isset($DBV['target'])) ? $DBV['target'] : "0"; $DBV['url'] = (isset($DBV['url'])) ? $DBV['url'] : ""; $DBV['sort'] = (isset($DBV['sort'])) ? $DBV['sort'] : ""; $smarty->assign("DBV", $DBV); return; }
四、在樣板製作表單
{* nav_m.php and op_form *} {if $WEB.file_name == "nav_m.php" and $op == "op_form"} <div class="container" style="margin-top:20px;"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">{$DBV.form_title}</h3> </div> <div class="panel-body"> <form action="nav_m.php" method="post"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <input type="text" class="form-control" id="title " name="title" value="{$DBV.title}" placeholder="標題"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">外連狀態</label> <input type='radio' name='target' id='target_1' value='1' {if $DBV.target==1}checked{/if} > <label for='target_1'>是</label> <input type='radio' name='target' id='target_0' value='0' {if $DBV.target==0}checked{/if}> <label for='target_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <input type='radio' name='enable' id='enable_1' value='1' {if $DBV.enable==1}checked{/if} > <label for='enable_1'>是</label> <input type='radio' name='enable' id='enable_0' value='0' {if $DBV.enable==0}checked{/if}> <label for='enable_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <input type="text" class="form-control" id="sort" name="sort" value="{$DBV.sort}" placeholder="排序"> </div> </div> </div> <div class="form-group"> <label>網址</label> <input type="text" class="form-control" id="url" name="url" value="{$DBV.url}" placeholder="網址"> </div> <!--用來控制程式流程--> <input type="hidden" name="op" value="{$DBV.op}"> <input type="hidden" name="sn" value="{$DBV.sn}"> <button type="submit" class="btn btn-default">送出</button> </form> </div> </div> </div> {/if}
表單說明:https://www.ugm.com.tw/modules/tad_book3/page.php?tbdsn=142
<form action="xxx.php" method="post"> <!--用來控制程式流程--> <input type="hidden" name="op" value="{$DBV.op}"> <input type="hidden" name="sn" value="{$DBV.sn}"> <button type="submit" class="btn btn-default">送出</button> </form>
<div class="form-group"> <label>標題</label> <input type="text" class="form-control" id="title " name="title" value="{$DBV.title}" placeholder="標題"> </div>sort
<div class="form-group"> <label>排序</label> <input type="text" class="form-control" id="sort" name="sort" value="{$DBV.sort}" placeholder="排序"> </div>
<div class="form-group"> <label>網址</label> <input type="text" class="form-control" id="url" name="url" value="{$DBV.url}" placeholder="網址"> </div>
<div class="form-group"> <label>標題</label> <input type="password" class="form-control" id="password" name="password" placeholder="標題"> <p class="help-block">備註</p> </div>
<div class="form-group"> <label style="display:block;">啟用狀態</label> <input type='radio' name='enable' id='enable_1' value='1' {if $DBV.enable==1}checked{/if} > <label for='enable_1'>是</label> <input type='radio' name='enable' id='enable_0' value='0' {if $DBV.enable==0}checked{/if}> <label for='enable_0'>否</label> </div>
<div class="form-group"> <label style="display:block;">外連狀態</label> <input type='radio' name='target' id='target_1' value='1' {if $DBV.target==1}checked{/if} > <label for='target_1'>是</label> <input type='radio' name='target' id='target_0' value='0' {if $DBV.target==0}checked{/if}> <label for='target_0'>否</label> </div>
<div class="form-group"> <label><{$smarty.const._MD_UGMTRIP_PROD_KIND}></label> <select name="kind" class="form-control" size="1"> <{$DBV.kind_option}> </select> </div>
kind程式端
#定義常用變數 $TBL['name']="show_prod";//資料表名稱 $TBL['kind']="kind_prod";//分類
op_form()
$DBV['kind'] = (isset($DBV['kind'])) ? $DBV['kind'] : ""; $DBV['kind_option'] = get_kind_prod_option($DBV['kind']);
######################################## # 得到商品類別選項 ######################################## function get_kind_prod_option($kind="") { global $mysqli,$smarty,$TBL; $sql = "select sn,title from `show_kind` where `kind`='{$TBL['kind']}' and `enable`='1' "; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $options=""; while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $selected = ($kind == $row['sn'])?" selected":""; $options .="<option value='{$row['sn']}'{$selected}>{$row['title']}</option>\n"; } return $options; }
<!-- 摘要--> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>摘要</label> <textarea class="form-control" rows="5" id="summary" name="summary">{$DBV.summary}</textarea> </div> </div> </div>內容(網頁編輯器)
<script src="{$smarty.const.WEB_URL}/class/ckeditor/ckeditor.js"></script> <!-- 內容--> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>內容</label> <textarea class="form-control" rows="5" id="content" name="content">{$DBV.content}</textarea> </div> </div> </div> <script> CKEDITOR.replace( 'content' ); </script>
<script src="{$smarty.const.WEB_URL}/class/My97DatePicker/WdatePicker.js" type="text/javascript"></script> <div class="col-md-3"> <div class="form-group"> <label>日期</label> {$DBV.date} </div> </div>
<div class="row"> <div class="col-md-9"> <div class="form-group"> <label>上傳圖片</label> <input name='file' type="file" id="file" class="form-control" accept="image/*" > </div> </div> {if $DBV.file_name} <div class="col-md-3"> <img src="{$DBV['file_name']}" alt="{$DBV.title}" class="img-responsive"> </div> {/if} </div>
<div class="container" style="margin-top:20px;"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> </div> </div> </div>
<div class="row"> <div class="col-md-6"> </div> <div class="col-md-6"> </div> </div>
可關閉的警告視窗
<div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Warning!</strong> Better check yourself, you're not looking too good. </div>
SweetAlert for Bootstrap
官網:http://lipis.github.io/bootstrap-sweetalert/
安裝:下載套件,解壓縮至 class目錄下
引入CSS
<link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" />
引入JS
<script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script>
設定插件
<script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='nav_m.php?op=op_delete&sn=' + sn; }); } </script>
列表按鈕
<button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger">刪除</button>
#新增記錄 case "op_insert": op_insert(); redirect_header("index.php",3000,"新增資料成功!!"); break;
######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); # nav_home => 首頁的選單 $_POST['kind'] = "nav_home"; $sql = "insert into `show_kind` (`title`, `target`, `enable`, `sort`,`url`,`kind`) VALUES ('{$_POST['title']}', '{$_POST['target']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['url']}', '{$_POST['kind']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 return $sn; }
一、流程
#顯示單筆 case "op_show": op_show($sn); break;
當新增、編輯記錄完成後,則顯示單筆記錄。
因此在新增的流程修改為:
#新增記錄 case "op_insert": $sn=op_insert(); redirect_header("nav_m.php?op=op_show&sn={$sn}",3000,"新增資料成功!!"); break;
二、函數
######################################## # 顯示單筆 ######################################## function op_show($sn="") { global $mysqli,$smarty; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); #取得單筆記錄,可以寫成函數 $sql = "select * from `show_kind` where `sn`='{$sn}' and `kind`='nav_home'"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = $DBV['enable'] ? "是":"<span style='color:red;'>否</span>"; $DBV['target'] = $DBV['target'] ? "是":"<span style='color:red;'>否</span>"; $smarty->assign("DBV", $DBV); return; }
三、樣板
{* 選單管理 顯示單筆 *} {if $WEB.file_name == "nav_m.php" and $op == "op_show"} <div class="container" style="margin-top:20px;"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">顯示單筆</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <div class="form-control">{$DBV.title}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">外連狀態</label> <div class="form-control">{$DBV.target}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <div class="form-control">{$DBV.enable}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <div class="form-control">{$DBV.sort}</div> </div> </div> </div> <div class="form-group"> <label>網址</label> <div class="form-control">{$DBV.url}</div> </div> </div> </div> </div> {/if}
一、列表
一、流程
#列表 default: $op="op_list"; op_list(); break;
二、函數
######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty; #取得所有記錄 $sql = "select * from `show_kind` where `kind`='nav_home' order by `sort` "; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['target'] = $row['target'] ? "是":"<span style='color:red;'>否</span>"; $DBV[]= $row; } $smarty->assign("DBV", $DBV); return; }
三、樣板
{* 選單管理 列表 *} {if $WEB.file_name == "nav_m.php" and $op == "op_list"} <div class="container" style="margin-top:20px;"> <table class="table "> <thead> <tr> <th>標題</th> <th>網址</th> <th>外連狀態</th> <th>啟用狀態</th> <th> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary">新增</button> </th> </tr> </thead> <tbody> {foreach from=$DBV item=row} <tr> <th>{$row.title}</th> <th>{$row.url}</th> <th>{$row.target}</th> <th>{$row.enable}</th> <th> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger">刪除</button> </th> </tr> {/foreach} </tbody> </table> </div> {/if}
#表單 case "op_form": op_form($sn); break;
這裡仍然使用 op_form($sn=""),但程式須修改
#抓取預設值 if($sn) { #編輯 $DBV=get_show_kind($sn);//取得單筆記錄 $DBV['op'] = "op_update"; $DBV['form_title'] = "編輯選單"; }else { #新增 $DBV=array(); $DBV['op'] = "op_insert"; $DBV['form_title'] = "新增選單"; }
取得單筆記錄
######################################## #取得單筆記錄 ######################################## function get_show_kind($sn="") { global $mysqli; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $sql = "select * from `show_kind` where `sn`='{$sn}' and `kind`='nav_home'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = intval($DBV['enable']); $DBV['target'] = intval($DBV['target']); return $DBV; }
和新增表單相同,故不用處理
一、流程
#更新記錄 case "op_update": $sn=op_update($sn); redirect_header("nav_m.php?op=op_show&sn={$sn}",3000,"更新資料成功!!"); break;
二、函數
######################################## # 更新記錄 ######################################## function op_update($sn="") { global $mysqli; if(!$sn)redirect_header("index.php",3000,"更新記錄錯誤!!"); #資料過濾 $_POST['sn'] = intval($_POST['sn']); $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $sql = "update `show_kind` set `title` = '{$_POST['title']}' , `target` = '{$_POST['target']}', `enable` = '{$_POST['enable']}', `url` = '{$_POST['url']}', `sort` = '{$_POST['sort']}' where sn='{$_POST['sn']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return $sn; }
一、流程
#刪除記錄 case "op_delete": op_delete($sn); redirect_header("index.php",3000,"刪除記錄成功!!"); exit; break;
二、函數
############################################################################### # 刪除資料 ############################################################################### function op_delete($sn="") { global $mysqli; if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!"); #檢查 $sql = "delete from `show_kind` where `sn`='{$sn}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; }
三、樣板(列表的樣板)
{literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='nav_m.php?op=op_delete&sn=' + sn; }); } </script> {/literal}
<button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger">刪除</button>
#PHP 5.2.9以後 $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); if ($mysqli->connect_error) { die('無法連上資料庫 (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } #設定資料庫語系 $mysqli->set_charset("utf8");
$mysqli->close();
$mysqli->query("insert into,update delete") //查詢 $mysqli->affected_row //傳回更改筆數 $mysqli->insert_id //傳回insert 指令所產生之流水號
$result->num_rows //查詢結果的資料筆數 $result->field_count //欄位數量 $mysqli->errno $mysqli->error //取得select時錯誤訊息
$row=$result->fetch_row(); //陣列形態,可用$row[$n]存取 $row=$result->fetch_array(); //關聯陣列,用$row[$n]或$row[$colname]存取 //,名稱區分大小寫 $row=$result->fetch_assoc(); //關聯陣列,只能用$row[$colname]存取 $row=$result->fetch_abject(); //以物件方式存取,$row->colname ##每次呼叫都會傳回下一筆,直到最後傳回FALSE $result->data_seek($row_number)跳到指定欄位
#資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']);//字串 $_POST['target'] = intval($_POST['target']);//數字
#過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號
######################################## # 檢查資料表是否存在 ######################################## function chk_isTable($tbl_name="") { global $mysqli; if(!$tbl_name)return; $sql = "SHOW TABLES LIKE '{$tbl_name}'"; //die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); if ($result->num_rows)return true; //欄位存在 return false;//欄位不存在 }
######################################## # 檢查某欄位是否存在 ######################################## function chk_isColumn($col_name="",$tbl_name="") { global $mysqli; if(!$col_name and $tbl_name)return; //SHOW COLUMNS FROM `show_kind` LIKE 'sn1' $sql = "SHOW COLUMNS FROM `{$tbl_name}` LIKE '{$col_name}'"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); if ($result->num_rows)return true; //欄位存在 return false;//欄位不存在 }
defined('WEB_PATH') || die("WEB_PATH root path not defined");
############################################################################### # 取得目前網址 ############################################################################### if(!function_exists("getCurrentUrl")){ function getCurrentUrl(){ global $_SERVER; $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')=== FALSE ? 'http' : 'https'; $host = $_SERVER['HTTP_HOST']; $script = $_SERVER['SCRIPT_NAME']; $params = $_SERVER['QUERY_STRING']?'?' . $_SERVER['QUERY_STRING']:""; $currentUrl = $protocol . '://' . $host . $script . $params; return $currentUrl;; } }列表流程
//預設動作 default: # ---- 目前網址 ---- $_SESSION['CurrentUrl']=getCurrentUrl(); $op="op_list"; op_list(); break;當程式有需要回到列表時,只要轉向至 $_SESSION['CurrentUrl'] 即可
<div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> </div>
<button onclick="window.location.href='?op=op_form&sn={$DBV.sn}'" type="button" class="btn btn-success">編輯</button>
{* 選單管理 列表 *} {if $WEB.file_name == "nav_m.php" and $op == "op_list"} {literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='nav_m.php?op=op_delete&sn=' + sn; }); } </script> {/literal} <div class="container" style="margin-top:20px;"> <h2 class="text-center">選單管理</h2> <table class="table table-bordered table-hover list-table"> <thead> <tr class="active"> <th class="text-center col-md-3">標題</th> <th class="text-center col-md-4">網址</th> <th class="text-center col-md-1">排序</th> <th class="text-center col-md-1">外連</th> <th class="text-center col-md-1">啟用</th> <th class="text-center col-md-2"> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary btn-xs">新增</button> </th> </tr> </thead> <tbody> {foreach from=$DBV item=row} <tr> <td>{$row.title}</td> <td>{$row.url}</td> <td class="text-center">{$row.sort}</td> <td class="text-center">{$row.target}</td> <td class="text-center">{$row.enable}</td> <td class="text-center"> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning btn-xs">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success btn-xs">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger btn-xs">刪除</button> </td> </tr> {/foreach} </tbody> </table> </div> {/if}
<?php #取得所有啟用的記錄 $sql = "select * from `show_kind` where `kind`='nav_home' and `enable`='1' order by `sort` "; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql); $nav_body=""; while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['target'] = $row['target'] ? " target='_blank'":""; $nav_body .= "<li><a href='{$row['url']}'{$row['target']}>{$row['title']}</a></li>"; } $nav=" <!--導覽列 start--> <nav class='navbar navbar-default' role='navigation' style='margin-bottom:0;'> <div class='container'> <!-- Brand and toggle get grouped for better mobile display --> <div class='navbar-header'> <button type='button' class='navbar-toggle collapsed' data-toggle='collapse' data-target='#bs-example-navbar-collapse-1'> <span class='sr-only'>Toggle navigation</span> <span class='icon-bar'></span> <span class='icon-bar'></span> <span class='icon-bar'></span> </button> <a class='navbar-brand' href='index.php'>{$WEB['title']}</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class='collapse navbar-collapse' id='bs-example-navbar-collapse-1'> <ul class='nav navbar-nav navbar-right'> {$nav_body} </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav --> "; #將變數送至樣版引擎 $smarty->assign("nav" , $nav);
#定義常用變數 $TBL['name']="show_kind";//資料表名稱 $TBL['kind']="nav_home";//分類
######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli,$TBL; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']);//字串 $_POST['target'] = intval($_POST['target']);//數字 $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); # nav_home => 首頁的選單 $_POST['kind'] = $TBL['kind']; $sql = "insert into `{$TBL['name']}` (`title`, `target`, `enable`, `sort`,`url`,`kind`) VALUES ('{$_POST['title']}', '{$_POST['target']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['url']}', '{$_POST['kind']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 return $sn;//傳回 $sn }
######################################## # 更新記錄 ######################################## function op_update($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"更新記錄錯誤!!"); #資料過濾 $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $sql = "update `{$TBL['name']}` set `title` = '{$_POST['title']}' , `target` = '{$_POST['target']}', `enable` = '{$_POST['enable']}', `url` = '{$_POST['url']}', `sort` = '{$_POST['sort']}' where sn='{$_POST['sn']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; }
############################################################################### # 刪除資料 ############################################################################### function op_delete($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!"); #檢查 $sql = "delete from `{$TBL['name']}` where `sn`='{$sn}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; }
######################################## # 取得單筆記錄 ######################################## function get_show_kind($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); #取得單筆記錄,可以寫成函數 $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql); $DBV = $result->fetch_assoc(); return $DBV; }
######################################## # 顯示單筆 ######################################## function op_show($sn="") { global $mysqli,$smarty; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $DBV=get_show_kind($sn);//取得單筆記錄 #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = $DBV['enable'] ? "是":"<span style='color:red;'>否</span>"; $DBV['target'] = $DBV['target'] ? "是":"<span style='color:red;'>否</span>"; $smarty->assign("DBV", $DBV); return; }
######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' order by `sort` "; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql); $DBV=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['target'] = $row['target'] ? "是":"<span style='color:red;'>否</span>"; $DBV[]= $row; } $smarty->assign("DBV", $DBV); return; }
##################################################################################### # 自動取得(排序欄位,資料表)的最新排序 # get_max_sort_show_kind($col,$TBL) # (排序欄位,資料表)# ##################################################################################### if(!function_exists("get_max_sort_show_kind")){ function get_max_sort_show_kind($col="sort",$TBL=""){ global $mysqli; if(empty($col) or empty($TBL))return; $sql = "select max({$col}) from `{$TBL['name']}` where kind='{$TBL['kind']}'"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); list($sort)=$result->fetch_row(); return ++$sort; } }
######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli,$TBL; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']);//字串 $_POST['target'] = intval($_POST['target']);//數字 $_POST['enable'] = intval($_POST['enable']); //$_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $_POST['sort'] = get_max_sort_show_kind("sort",$TBL);//直接寫入最大值 # nav_home => 首頁的選單 $_POST['kind'] = $TBL['kind']; $sql = "insert into `{$TBL['name']}` (`title`, `target`, `enable`, `sort`,`url`,`kind`) VALUES ('{$_POST['title']}', '{$_POST['target']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['url']}', '{$_POST['kind']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 return $sn;//傳回 $sn }
<?php require_once 'head.php'; #定義常用的變數 $TBL['name']="show_kind";//資料表 $TBL['kind']="nav_home";//分類 #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; $sn = isset($_REQUEST['sn'])?intval($_REQUEST['sn']):""; #程式流程 switch($op){ #新增記錄 case "op_insert": $sn=op_insert(); redirect_header("nav_m.php?op=op_show&sn={$sn}",3000,"新增資料成功!!"); exit; break; #更新記錄 case "op_update": $sn=op_update($sn); redirect_header("nav_m.php?op=op_show&sn={$sn}",3000,"更新資料成功!!"); exit; break; #刪除記錄 case "op_delete": op_delete($sn); redirect_header($_SESSION['CurrentUrl'],3000,"刪除記錄成功!!"); exit; break; #表單 case "op_form": op_form($sn); break; #顯示單筆 case "op_show": op_show($sn); break; #列表 default: # ---- 目前網址 ---- $_SESSION['CurrentUrl']=getCurrentUrl(); $op="op_list"; op_list(); break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); /* $WEB['theme_name'] = "admin"; WEB['title'] = "網站名稱"; $WEB['file_name'] = basename ($_SERVER['PHP_SELF']); */ #變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli,$TBL; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); //$_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $_POST['sort'] = get_max_sort_show_kind("sort",$TBL); # nav_home => 首頁的選單 $_POST['kind'] = $TBL['kind']; $sql = "insert into `{$TBL['name']}` (`title`, `target`, `enable`, `sort`,`url`,`kind`) VALUES ('{$_POST['title']}', '{$_POST['target']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['url']}', '{$_POST['kind']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 return $sn; } ######################################## # 更新記錄 ######################################## function op_update($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"更新記錄錯誤!!"); #資料過濾 $_POST['sn'] = intval($_POST['sn']); $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $sql = "update `{$TBL['name']}` set `title` = '{$_POST['title']}' , `target` = '{$_POST['target']}', `enable` = '{$_POST['enable']}', `url` = '{$_POST['url']}', `sort` = '{$_POST['sort']}' where sn='{$_POST['sn']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return $sn; } ############################################################################### # 刪除資料 ############################################################################### function op_delete($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!"); #檢查 $sql = "delete from `{$TBL['name']}` where `sn`='{$sn}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; } ######################################## #取得單筆記錄 ######################################## function get_show_kind($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = intval($DBV['enable']); $DBV['target'] = intval($DBV['target']); return $DBV; } ######################################## # 表單 ######################################## function op_form($sn="") { global $mysqli,$smarty; #抓取預設值 if($sn) { #編輯 $DBV=get_show_kind($sn);//取得單筆記錄 $DBV['op'] = "op_update"; $DBV['form_title'] = "編輯選單"; //print_r($DBV);die(); }else { #新增 $DBV=array(); $DBV['op'] = "op_insert"; $DBV['form_title'] = "新增選單"; } //預設值設定 //標題 title (text)、網址 url (text)、是否外連 target (radio)、是否啟用 enable (radio)、排序 sort(text) $DBV['sn'] = (isset($DBV['sn'])) ? $DBV['sn'] : ""; $DBV['title'] = (isset($DBV['title'])) ? $DBV['title'] : ""; $DBV['enable'] = (isset($DBV['enable'])) ? $DBV['enable'] : "1"; $DBV['target'] = (isset($DBV['target'])) ? $DBV['target'] : "0"; $DBV['url'] = (isset($DBV['url'])) ? $DBV['url'] : ""; $DBV['sort'] = (isset($DBV['sort'])) ? $DBV['sort'] : ""; $smarty->assign("DBV", $DBV); return; } ######################################## # op_show ######################################## function op_show($sn="") { global $mysqli,$smarty,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); #取得單筆記錄,可以寫成函數 #sn ofsn kind title sort enable url target col_sn content $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = $DBV['enable'] ? "是":"<span style='color:red;'>否</span>"; $DBV['target'] = $DBV['target'] ? "是":"<span style='color:red;'>否</span>"; $smarty->assign("DBV", $DBV); return; } ######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' order by `sort` "; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['target'] = $row['target'] ? "是":"<span style='color:red;'>否</span>"; $DBV[]= $row; } $smarty->assign("DBV", $DBV); return; }
{* nav_m.php begin*} {* 選單管理 表單 *} {if $WEB.file_name == "nav_m.php" and $op == "op_form"} <div class="container" style="margin-top:20px;"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">{$DBV.form_title}</h3> </div> <div class="panel-body"> <form action="nav_m.php" method="post"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <input type="text" class="form-control" id="title " name="title" value="{$DBV.title}" placeholder="標題"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">外連狀態</label> <input type='radio' name='target' id='target_1' value='1' {if $DBV.target==1}checked{/if} > <label for='target_1'>是</label> <input type='radio' name='target' id='target_0' value='0' {if $DBV.target==0}checked{/if}> <label for='target_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <input type='radio' name='enable' id='enable_1' value='1' {if $DBV.enable==1}checked{/if} > <label for='enable_1'>是</label> <input type='radio' name='enable' id='enable_0' value='0' {if $DBV.enable==0}checked{/if}> <label for='enable_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <input type="text" class="form-control" id="sort" name="sort" value="{$DBV.sort}" placeholder="排序"> </div> </div> </div> <div class="form-group"> <label>網址</label> <input type="text" class="form-control" id="url" name="url" value="{$DBV.url}" placeholder="網址"> </div> <!--用來控制程式流程--> <input type="hidden" name="op" value="{$DBV.op}"> <input type="hidden" name="sn" value="{$DBV.sn}"> <button type="submit" class="btn btn-default">送出</button> </form> </div> </div> </div> {/if} {* 選單管理 顯示單筆 *} {if $WEB.file_name == "nav_m.php" and $op == "op_show"} <div class="container" style="margin-top:20px;"> <div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> <button onclick="window.location.href='?op=op_form&sn={$DBV.sn}'" type="button" class="btn btn-success">編輯</button> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">顯示單筆</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <div class="form-control">{$DBV.title}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">外連狀態</label> <div class="form-control">{$DBV.target}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <div class="form-control">{$DBV.enable}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <div class="form-control">{$DBV.sort}</div> </div> </div> </div> <div class="form-group"> <label>網址</label> <div class="form-control">{$DBV.url}</div> </div> </div> </div> </div> {/if} {* 選單管理 列表 *} {if $WEB.file_name == "nav_m.php" and $op == "op_list"} {literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='nav_m.php?op=op_delete&sn=' + sn; }); } </script> {/literal} <div class="container" style="margin-top:20px;"> <h2 class="text-center">選單管理</h2> <table class="table table-bordered table-hover list-table"> <thead> <tr class="active"> <th class="text-center col-md-3">標題</th> <th class="text-center col-md-4">網址</th> <th class="text-center col-md-1">排序</th> <th class="text-center col-md-1">外連</th> <th class="text-center col-md-1">啟用</th> <th class="text-center col-md-2"> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary btn-xs">新增</button> </th> </tr> </thead> <tbody> {foreach from=$DBV item=row} <tr> <td>{$row.title}</td> <td>{$row.url}</td> <td class="text-center">{$row.sort}</td> <td class="text-center">{$row.target}</td> <td class="text-center">{$row.enable}</td> <td class="text-center"> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning btn-xs">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success btn-xs">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger btn-xs">刪除</button> </td> </tr> {/foreach} </tbody> </table> </div> {/if} {* nav_m.php end *}
<?php require_once 'head.php'; #定義常用的變數 $TBL['name']="show_kind";//資料表 $TBL['kind']="slider_home";//分類 #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; $sn = isset($_REQUEST['sn'])?intval($_REQUEST['sn']):""; #程式流程 switch($op){ #新增記錄 case "op_insert": $sn=op_insert(); redirect_header("nav_m.php?op=op_show&sn={$sn}",3000,"新增資料成功!!"); exit; break; #更新記錄 case "op_update": $sn=op_update($sn); redirect_header("nav_m.php?op=op_show&sn={$sn}",3000,"更新資料成功!!"); exit; break; #刪除記錄 case "op_delete": op_delete($sn); redirect_header($_SESSION['CurrentUrl'],3000,"刪除記錄成功!!"); exit; break; #表單 case "op_form": op_form($sn); break; #顯示單筆 case "op_show": op_show($sn); break; #列表 default: # ---- 目前網址 ---- $_SESSION['CurrentUrl']=getCurrentUrl(); $op="op_list"; op_list(); break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); /* $WEB['theme_name'] = "admin"; WEB['title'] = "網站名稱"; $WEB['file_name'] = basename ($_SERVER['PHP_SELF']); */ #變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli,$TBL; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); //$_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $_POST['sort'] = get_max_sort_show_kind("sort",$TBL); # nav_home => 首頁的選單 $_POST['kind'] = $TBL['kind']; $sql = "insert into `{$TBL['name']}` (`title`, `target`, `enable`, `sort`,`url`,`kind`) VALUES ('{$_POST['title']}', '{$_POST['target']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['url']}', '{$_POST['kind']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 return $sn; } ######################################## # 更新記錄 ######################################## function op_update($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"更新記錄錯誤!!"); #資料過濾 $_POST['sn'] = intval($_POST['sn']); $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['target'] = intval($_POST['target']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['url'] = $mysqli->real_escape_string($_POST['url']); $sql = "update `{$TBL['name']}` set `title` = '{$_POST['title']}' , `target` = '{$_POST['target']}', `enable` = '{$_POST['enable']}', `url` = '{$_POST['url']}', `sort` = '{$_POST['sort']}' where sn='{$_POST['sn']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return $sn; } ############################################################################### # 刪除資料 ############################################################################### function op_delete($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!"); #檢查 $sql = "delete from `{$TBL['name']}` where `sn`='{$sn}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; } ######################################## #取得單筆記錄 ######################################## function get_show_kind($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = intval($DBV['enable']); $DBV['target'] = intval($DBV['target']); return $DBV; } ######################################## # 表單 ######################################## function op_form($sn="") { global $mysqli,$smarty; #抓取預設值 if($sn) { #編輯 $DBV=get_show_kind($sn);//取得單筆記錄 $DBV['op'] = "op_update"; $DBV['form_title'] = "編輯選單"; //print_r($DBV);die(); }else { #新增 $DBV=array(); $DBV['op'] = "op_insert"; $DBV['form_title'] = "新增選單"; } //預設值設定 //標題 title (text)、網址 url (text)、是否外連 target (radio)、是否啟用 enable (radio)、排序 sort(text) $DBV['sn'] = (isset($DBV['sn'])) ? $DBV['sn'] : ""; $DBV['title'] = (isset($DBV['title'])) ? $DBV['title'] : ""; $DBV['enable'] = (isset($DBV['enable'])) ? $DBV['enable'] : "1"; $DBV['target'] = (isset($DBV['target'])) ? $DBV['target'] : "0"; $DBV['url'] = (isset($DBV['url'])) ? $DBV['url'] : ""; $DBV['sort'] = (isset($DBV['sort'])) ? $DBV['sort'] : ""; $smarty->assign("DBV", $DBV); return; } ######################################## # op_show ######################################## function op_show($sn="") { global $mysqli,$smarty,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); #取得單筆記錄,可以寫成函數 #sn ofsn kind title sort enable url target col_sn content $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = $DBV['enable'] ? "是":"<span style='color:red;'>否</span>"; $DBV['target'] = $DBV['target'] ? "是":"<span style='color:red;'>否</span>"; $smarty->assign("DBV", $DBV); return; } ######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' order by `sort` "; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['target'] = $row['target'] ? "是":"<span style='color:red;'>否</span>"; $DBV[]= $row; } $smarty->assign("DBV", $DBV); return; }
{* slider.php begin*} {* 輪播圖管理 表單 *} {if $WEB.file_name == "slider.php" and $op == "op_form"} <div class="container" style="margin-top:20px;"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">{$DBV.form_title}</h3> </div> <div class="panel-body"> <form action="slider.php" method="post"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <input type="text" class="form-control" id="title " name="title" value="{$DBV.title}" placeholder="標題"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">外連狀態</label> <input type='radio' name='target' id='target_1' value='1' {if $DBV.target==1}checked{/if} > <label for='target_1'>是</label> <input type='radio' name='target' id='target_0' value='0' {if $DBV.target==0}checked{/if}> <label for='target_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <input type='radio' name='enable' id='enable_1' value='1' {if $DBV.enable==1}checked{/if} > <label for='enable_1'>是</label> <input type='radio' name='enable' id='enable_0' value='0' {if $DBV.enable==0}checked{/if}> <label for='enable_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <input type="text" class="form-control" id="sort" name="sort" value="{$DBV.sort}" placeholder="排序"> </div> </div> </div> <div class="form-group"> <label>網址</label> <input type="text" class="form-control" id="url" name="url" value="{$DBV.url}" placeholder="網址"> </div> <!--用來控制程式流程--> <input type="hidden" name="op" value="{$DBV.op}"> <input type="hidden" name="sn" value="{$DBV.sn}"> <button type="submit" class="btn btn-default">送出</button> </form> </div> </div> </div> {/if} {* 輪播圖管理 顯示單筆 *} {if $WEB.file_name == "slider.php" and $op == "op_show"} <div class="container" style="margin-top:20px;"> <div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> <button onclick="window.location.href='?op=op_form&sn={$DBV.sn}'" type="button" class="btn btn-success">編輯</button> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">顯示單筆</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <div class="form-control">{$DBV.title}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">外連狀態</label> <div class="form-control">{$DBV.target}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <div class="form-control">{$DBV.enable}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <div class="form-control">{$DBV.sort}</div> </div> </div> </div> <div class="form-group"> <label>網址</label> <div class="form-control">{$DBV.url}</div> </div> </div> </div> </div> {/if} {* 輪播圖管理 列表 *} {if $WEB.file_name == "slider.php" and $op == "op_list"} {literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='slider.php?op=op_delete&sn=' + sn; }); } </script> {/literal} <div class="container" style="margin-top:20px;"> <h2 class="text-center">輪播圖管理</h2> <table class="table table-bordered table-hover list-table"> <thead> <tr class="active"> <th class="text-center col-md-3">標題</th> <th class="text-center col-md-4">網址</th> <th class="text-center col-md-1">排序</th> <th class="text-center col-md-1">外連</th> <th class="text-center col-md-1">啟用</th> <th class="text-center col-md-2"> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary btn-xs">新增</button> </th> </tr> </thead> <tbody> {foreach from=$DBV item=row} <tr> <td>{$row.title}</td> <td>{$row.url}</td> <td class="text-center">{$row.sort}</td> <td class="text-center">{$row.target}</td> <td class="text-center">{$row.enable}</td> <td class="text-center"> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning btn-xs">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success btn-xs">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger btn-xs">刪除</button> </td> </tr> {/foreach} </tbody> </table> </div> {/if} {* slider.php end *}
四、增加後台選單
<li><a href='slider.php'>輪播圖管理</a></li>
<li><a href='slider.php'>輪播圖管理</a></li>
<?php require_once 'head.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; $sn = isset($_REQUEST['sn'])?intval($_REQUEST['sn']):""; #程式流程 switch($op){ #顯示單筆 case "op_show": die($op); break; #更新 default: $op="op_list"; $msg=op_list(); if($msg) { redirect_header("index.php",3000,"更新系統成功!!"); } else { redirect_header("index.php",3000,"更新系統失敗!!"); } break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); /* $WEB['theme_name'] = "admin"; WEB['title'] = "網站名稱"; $WEB['file_name'] = basename ($_SERVER['PHP_SELF']); */ #變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # 更新主程式 ######################################## function op_list() { global $mysqli; #檢查資料夾 mk_dir(WEB_PATH."/uploads"); mk_dir(WEB_PATH."/uploads/slider"); //-------- 資料表 ------ #檢查資料表(show_kind) if(!chk_isTable("show_kind")) go_update1(); #檢查資料表(show_file) if(!chk_isTable("show_files")) go_update2(); //-------- 資料表 end------ //-------- 欄位 ------ //if(!chk_isColumn("sn1","show_kind")) go_update3(); //-------- 欄位 end------ return true; } ######################################## # 建立資料表 show_kind ######################################## function go_update1() { global $mysqli; $sql=" CREATE TABLE `show_kind` ( `sn` smallint(5) unsigned not null auto_increment comment 'sn', `ofsn` smallint(5) unsigned not null default 0 comment '父類別', `kind` varchar(255) not null default 'nav_home' comment '分類', `title` varchar(255) not null default '' comment '標題', `sort` smallint(5) unsigned not null default 0 comment '排序', `enable` enum('1','0') not null default '1' comment '狀態', `url` varchar(255) not null default '' comment '網址', `target` enum('0','1') not null default '0' comment '外連', `col_sn` int(10) unsigned not null default 0 comment 'col_sn', `content` text not null default '' comment '內容', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; "; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return true; } ######################################## # 建立資料表show_files ######################################## function go_update2() { global $mysqli; $sql=" CREATE TABLE `show_files` ( `sn` smallint(5) unsigned not null auto_increment comment 'sn', `col_name` varchar(255) not null default '' comment '欄位名稱', `col_sn` smallint(5) unsigned not null default 0 comment '欄位編號', `sort` smallint(5) unsigned not null default 0 comment '排序', `kind` enum('img','file') not null default 'img' comment '檔案種類', `file_name` varchar(255) not null default '' comment '檔案名稱', `file_type` varchar(255) not null default '' comment '檔案類型', `file_size` int(10) unsigned not null default 0 comment '檔案大小', `description` text not null default '' comment '檔案說明', `counter` mediumint(8) unsigned not null default 0 comment '下載人次', `sub_dir` varchar(255) not null default '' comment '檔案子路徑', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return true; } ######################################## # 在資料表show_kind 增加一個 sn1 欄位 ######################################## // function go_update3() // { // global $mysqli; // $sql="ALTER TABLE `show_kind` ADD `sn1` smallint(5) unsigned NOT NULL default 0 comment 'sn1'";//die($sql); // $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); // return true; // } ######################################## # 檢查某欄位是否存在(欄名,資料表) ######################################## function chk_isColumn($col_name="",$tbl_name="") { global $mysqli; if(!$col_name and $tbl_name)return; //SHOW COLUMNS FROM `show_kind` LIKE 'sn1' $sql = "SHOW COLUMNS FROM `{$tbl_name}` LIKE '{$col_name}'"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); if ($result->num_rows)return true; //欄位存在 return false;//欄位不存在 } ######################################## # 檢查資料表是否存在(資料表) ######################################## function chk_isTable($tbl_name="") { global $mysqli; if(!$tbl_name)return; $sql = "SHOW TABLES LIKE '{$tbl_name}'";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); if ($result->num_rows)return true; //欄位存在 return false;//欄位不存在 }
##################################################################################### # 建立目錄 ##################################################################################### if(!function_exists("mk_dir")){ function mk_dir($dir = "") { #若無目錄名稱秀出警告訊息 if (empty($dir)) { return; } #若目錄不存在的話建立目錄 if (!is_dir($dir)) { umask(000); //若建立失敗秀出警告訊息 mkdir($dir, 0777); } } }
<li><a href='update.php'>網站更新</a></li> <li><a href='../../mysql/adminer.php' target='_blank'>資料庫管理</a></li>
一、檔案上傳
二、樣板增加「上傳表單」
enctype="multipart/form-data"
<input type="file" name="XXX" >
<input id="file" type="file" class="form-control" accept="image/*" >
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
enctype="multipart/form-data"
<div class="form-group"> <label>上傳圖片</label> <input name='file' type="file" id="file" class="form-control" accept="image/*" > </div>
因為有「 accept="image/*」所以使用者預設只能看到圖片,不過仍可以切換至「所有檔案」上傳其他類型檔案
/* $_FILES['file']['name']:上傳檔案原始名稱。 $_FILES['file']['type']:檔案的 MIME 類型,例如“image/gif”。 $_FILES['file']['size']:已上傳檔案的大小,單位為bytes。 $_FILES['file']['tmp_name']:檔案被上傳後的臨時檔案名。 $_FILES['file']['error']:和該檔案上傳相關的錯誤代碼。 */ if($_FILES['file'] and !$_FILES['file']['error']) { $col_name=$_POST['kind'];//輪播圖的關鍵字 slider_home $col_sn=$sn;//相關流水號 $sort=1;//排序 $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//取得副檔名 $ext = strtolower($ext); //轉小寫 $sub_dir="/slider";//儲存位置 $file_name="slider_".$col_sn."_".$sort.".".$ext;//檔名 if($ext == "png" or $ext == "gif" or $ext == "jpg" or $ext == "jpeg" or $ext == "jpe") { $kind="img"; }else { $kind="file"; } #寫入資料表 show_files $sql = "insert into `show_files` (`col_name`, `col_sn`, `sort`, `kind`,`file_name`,`file_type`,`file_size`,`description`,`sub_dir`) VALUES ('{$col_name}', '{$col_sn}', '{$sort}', '{$kind}', '{$file_name}', '{$_FILES['file']['type']}','{$_FILES['file']['size']}', '{$_POST['title']}', '{$sub_dir}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $new_file= WEB_PATH."/uploads".$sub_dir."/".$file_name; #移動檔案 move_uploaded_file($_FILES['file']['tmp_name'] , $new_file); }
#取得圖片src $DBV['file_name'] = get_file_name_src($DBV['sn'],$TBL['kind']);取得圖片src 函數
######################################## # #取得圖片src ######################################## function get_file_name_src($col_sn,$col_name) { global $mysqli; if(!$col_sn or !$col_name)return; #這裡可以再寫成函數 取得圖片檔資料 $sql = "select * from `show_files` where `col_sn`='{$col_sn}' and `col_name`='{$col_name}' order by sort"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $row = $result->fetch_assoc(); #---------------- #圖片檔src $file_name = WEB_URL."/uploads".$row['sub_dir']."/".$row['file_name']; return $file_name; }
class
=
"img-responsive")
<div class="row"> <div class="col-md-9"> <div class="form-group"> <label>網址</label> <div class="form-control">{$DBV['url']}</div> </div> </div> {if $DBV.file_name} <div class="col-md-3"> <img src="{$DBV['file_name']}" alt="{$DBV.title}" class="img-responsive"> </div> {/if} </div>
#取得圖片src $DBV['file_name'] = get_file_name_src($DBV['sn'],$TBL['kind']);op_form($sn) 函數
#圖片src $DBV['file_name'] = (isset($DBV['file_name'])) ? $DBV['file_name'] : "";op_form 樣板
<div class="row"> <div class="col-md-9"> <div class="form-group"> <label>上傳圖片</label> <input name='file' type="file" id="file" class="form-control" accept="image/*" > </div> </div> {if $DBV.file_name} <div class="col-md-3"> <img src="{$DBV['file_name']}" alt="{$DBV.title}" class="img-responsive"> </div> {/if} </div>
######################################## # #取得圖片src ######################################## function get_file_name_src($col_sn,$col_name) { global $mysqli; if(!$col_sn or !$col_name)return; #這裡可以再寫成函數 取得圖片檔資料 $sql = "select * from `show_files` where `col_sn`='{$col_sn}' and `col_name`='{$col_name}' order by sort"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $row = $result->fetch_assoc(); #---------------- #圖片檔src $file_name = WEB_URL."/uploads".$row['sub_dir']."/".$row['file_name']; return $file_name; }=>
######################################## # #取得圖片 ######################################## function get_file_name($col_sn,$col_name) { global $mysqli; if(!$col_sn or !$col_name)return; # $sql = "select * from `show_files` where `col_sn`='{$col_sn}' and `col_name`='{$col_name}' order by sort"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $row = $result->fetch_assoc(); #---------------- return $row; } ######################################## # #取得圖片src ######################################## function get_file_name_src($col_sn,$col_name) { if(!$col_sn or !$col_name)return; $row = get_file_name($col_sn,$col_name); #---------------- #圖片檔src $file_name = $row['file_name'] ? WEB_URL."/uploads".$row['sub_dir']."/".$row['file_name']:""; return $file_name; }
/* $_FILES['file']['name']:上傳檔案原始名稱。 $_FILES['file']['type']:檔案的 MIME 類型,例如“image/gif”。 $_FILES['file']['size']:已上傳檔案的大小,單位為bytes。 $_FILES['file']['tmp_name']:檔案被上傳後的臨時檔案名。 $_FILES['file']['error']:和該檔案上傳相關的錯誤代碼。 */ if($_FILES['file'] and !$_FILES['file']['error']) { #刪除舊檔(資料表、實體檔案) delete_file_name($sn,$TBL['kind']); #----------------------- $col_name=$TBL['kind'];//輪播圖的關鍵字 slider_home $col_sn=$sn;//相關流水號 $sort=1;//排序 $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//取得副檔名 $ext = strtolower($ext); //轉小寫 $sub_dir="/slider";//儲存位置 $file_name="slider_".$col_sn."_".$sort.".".$ext;//檔名 if($ext == "png" or $ext == "gif" or $ext == "jpg" or $ext == "jpeg" or $ext == "jpe") { $kind="img"; }else { $kind="file"; } #寫入資料表 show_files $sql = "insert into `show_files` (`col_name`, `col_sn`, `sort`, `kind`,`file_name`,`file_type`,`file_size`,`description`,`sub_dir`) VALUES ('{$col_name}', '{$col_sn}', '{$sort}', '{$kind}', '{$file_name}', '{$_FILES['file']['type']}','{$_FILES['file']['size']}', '{$_POST['title']}', '{$sub_dir}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $new_file= WEB_PATH."/uploads".$sub_dir."/".$file_name; #移動檔案 move_uploaded_file($_FILES['file']['tmp_name'] , $new_file); }
######################################## # 刪除圖片 ######################################## function delete_file_name($col_sn,$col_name) { global $mysqli; if(!$col_sn or !$col_name)return; #取得資料 $row = get_file_name($col_sn,$col_name); if($row){ #1. 刪除實體檔案 unlink(WEB_PATH."/uploads".$row['sub_dir']."/".$row['file_name']); #2. 刪除「show_files」記錄 $sql = "delete from `show_files` where `sn`='{$row['sn']}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); } return true; }流程
#更新記錄 case "op_update": $sn=op_update($sn); #刪除快取 $smarty->clearAllCache(); redirect_header("{$WEB['file_name']}?op=op_show&sn={$sn}",3000,"更新資料成功!!"); exit; break;
############################################################################### # 刪除資料 ############################################################################### function op_delete($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!"); #刪除舊檔(資料表、實體檔案) delete_file_name($sn,$TBL['kind']); #刪除 show_kind $sql = "delete from `{$TBL['name']}` where `sn`='{$sn}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; }
######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' order by `sort` ";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $rows=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['target'] = $row['target'] ? "是":"<span style='color:red;'>否</span>"; #取得圖片src $col_name = "slider_home"; $row['file_name'] = get_file_name_src($row['sn'],$col_name); $rows[]= $row; } $smarty->assign("DBV", $rows); return; }
{* 選單管理 列表 *} {if $WEB.file_name == "slider.php" and $op == "op_list"} {literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='slider.php?op=op_delete&sn=' + sn; }); } </script> {/literal} <div class="container" style="margin-top:20px;"> <h2 class="text-center">選單管理</h2> <table class="table table-bordered table-hover list-table"> <thead> <tr class="active"> <th class="text-center col-md-1">縮圖</th> <th class="text-center col-md-3">標題</th> <th class="text-center col-md-3">網址</th> <th class="text-center col-md-1">排序</th> <th class="text-center col-md-1">外連</th> <th class="text-center col-md-1">啟用</th> <th class="text-center col-md-2"> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary btn-xs">新增</button> </th> </tr> </thead> <tbody> {foreach from=$DBV item=row} <tr> <td>{if $row.file_name} <img src="{$row.file_name}" class="img-responsive">{/if}</td> <td>{$row.title}</td> <td>{$row.url}</td> <td class="text-center">{$row.sort}</td> <td class="text-center">{$row.target}</td> <td class="text-center">{$row.enable}</td> <td class="text-center"> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning btn-xs">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success btn-xs">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger btn-xs">刪除</button> </td> </tr> {/foreach} </tbody> </table> </div> {/if}
一、原本前台 theme.html 的語法
套件是放在「{literal}」裡面,所以應該無法放變數進來,所以把這段移回去程式裡面,再從程式用變數傳至樣板
二、著手套用修改
#定義常用變數 $TBL['name']="show_kind";//資料表名稱 $TBL['kind']="slider_home";//分類
流程控制
//預設動作 default: $op="op_list"; op_list(); break;
######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' order by `sort` ";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $rows=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['url'] = htmlspecialchars($row['url'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['target'] = $row['target'] ? "是":"<span style='color:red;'>否</span>"; #取得圖片src $col_name = "slider_home"; $row['file_name'] = get_file_name_src($row['sn'],$col_name); $rows[]= $row; } $smarty->assign("DBV", $rows); return; }
#函數 ######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' and `enable`='1' order by `sort` ";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); /* $backstretch_js=" <script type='text/javascript'> $(document).ready(function(){ $('.top-content').backstretch([ 'http://fakeimg.pl/1600x1200/ff0000/' , 'http://fakeimg.pl/1600x1200/00ff00/' , 'http://fakeimg.pl/1600x1200/0000ff/' ], {duration: 3000, fade: 750}); }); </script> "; */ $file_name=""; $col_name = "slider_home"; while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); $comma = $file_name ? ", ":""; #取得圖片src $file_name .= $comma. "'" .get_file_name_src($row['sn'],$col_name). "'"; } $backstretch_js=""; if($file_name){ $backstretch_js=" <script type='text/javascript'> \$(document).ready(function(){ \$('.top-content').backstretch([ {$file_name} ], {duration: 3000, fade: 750}); }); </script> "; } $smarty->assign("backstretch_js", $backstretch_js); return; }
{$backstretch_js}
http://campus-xoops.tn.edu.tw/modules/tad_book3/index.php?op=list_docs&tbsn=17
一、kind.php
<li><a href='kind.php'>商品類別管理</a></li>
二、增加商品資料表
CREATE TABLE `show_prod` ( `sn` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'prod_sn', `kind` smallint(5) unsigned NOT NULL default 0 COMMENT '分類', `title` varchar(255) NOT NULL default '' COMMENT '名稱', `summary` text NOT NULL default '' COMMENT '摘要', `content` text NOT NULL default '' COMMENT '內容', `price` int(10) unsigned NOT NULL default 0 COMMENT '價格', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', `date` int(10) unsigned NOT NULL default 0 COMMENT '建立日期', `sort` smallint(5) unsigned NOT NULL default 0 COMMENT '排序', `counter` int(10) unsigned NOT NULL default 0 COMMENT '人氣', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
<?php require_once 'head.php'; #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; $sn = isset($_REQUEST['sn'])?intval($_REQUEST['sn']):""; #程式流程 switch($op){ #顯示單筆 case "op_show": die($op); break; #更新 default: $op="op_list"; $msg=op_list(); if($msg) { redirect_header("index.php",3000,"更新系統成功!!"); } else { redirect_header("index.php",3000,"更新系統失敗!!"); } break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); /* $WEB['theme_name'] = "admin"; WEB['title'] = "網站名稱"; $WEB['file_name'] = basename ($_SERVER['PHP_SELF']); */ #變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # 更新主程式 ######################################## function op_list() { global $mysqli; #檢查資料夾 mk_dir(WEB_PATH."/uploads"); mk_dir(WEB_PATH."/uploads/slider"); //-------- 資料表 ------ #檢查資料表(show_kind) if(!chk_isTable("show_kind")) go_update1(); #檢查資料表(show_files) if(!chk_isTable("show_files")) go_update2(); #檢查資料表(show_prod) if(!chk_isTable("show_prod")) go_update3(); //-------- 資料表 end------ //-------- 欄位 ------ //if(!chk_isColumn("sn1","show_kind")) go_update3(); //-------- 欄位 end------ return true; } ######################################## # 建立資料表 show_kind ######################################## function go_update1() { global $mysqli; $sql=" CREATE TABLE `show_kind` ( `sn` smallint(5) unsigned not null auto_increment comment 'sn', `ofsn` smallint(5) unsigned not null default 0 comment '父類別', `kind` varchar(255) not null default 'nav_home' comment '分類', `title` varchar(255) not null default '' comment '標題', `sort` smallint(5) unsigned not null default 0 comment '排序', `enable` enum('1','0') not null default '1' comment '狀態', `url` varchar(255) not null default '' comment '網址', `target` enum('0','1') not null default '0' comment '外連', `col_sn` int(10) unsigned not null default 0 comment 'col_sn', `content` text not null default '' comment '內容', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; "; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return true; } ######################################## # 建立資料表show_files ######################################## function go_update2() { global $mysqli; $sql=" CREATE TABLE `show_files` ( `sn` smallint(5) unsigned not null auto_increment comment 'sn', `col_name` varchar(255) not null default '' comment '欄位名稱', `col_sn` smallint(5) unsigned not null default 0 comment '欄位編號', `sort` smallint(5) unsigned not null default 0 comment '排序', `kind` enum('img','file') not null default 'img' comment '檔案種類', `file_name` varchar(255) not null default '' comment '檔案名稱', `file_type` varchar(255) not null default '' comment '檔案類型', `file_size` int(10) unsigned not null default 0 comment '檔案大小', `description` text not null default '' comment '檔案說明', `counter` mediumint(8) unsigned not null default 0 comment '下載人次', `sub_dir` varchar(255) not null default '' comment '檔案子路徑', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return true; } ######################################## # 建立資料表show_prod ######################################## function go_update3() { global $mysqli; $sql=" CREATE TABLE `show_prod` ( `sn` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'prod_sn', `kind` smallint(5) unsigned NOT NULL default 0 COMMENT '分類', `title` varchar(255) NOT NULL default '' COMMENT '名稱', `summary` text NOT NULL default '' COMMENT '摘要', `content` text NOT NULL default '' COMMENT '內容', `price` int(10) unsigned NOT NULL default 0 COMMENT '價格', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', `date` int(10) unsigned NOT NULL default 0 COMMENT '建立日期', `sort` smallint(5) unsigned NOT NULL default 0 COMMENT '排序', `counter` int(10) unsigned NOT NULL default 0 COMMENT '人氣', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return true; } ######################################## # 在資料表show_kind 增加一個 sn1 欄位 ######################################## // function go_update3() // { // global $mysqli; // $sql="ALTER TABLE `show_kind` ADD `sn1` smallint(5) unsigned NOT NULL default 0 comment 'sn1'";//die($sql); // $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); // return true; // } ######################################## # 檢查某欄位是否存在(欄名,資料表) ######################################## function chk_isColumn($col_name="",$tbl_name="") { global $mysqli; if(!$col_name and $tbl_name)return; //SHOW COLUMNS FROM `show_kind` LIKE 'sn1' $sql = "SHOW COLUMNS FROM `{$tbl_name}` LIKE '{$col_name}'"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); if ($result->num_rows)return true; //欄位存在 return false;//欄位不存在 } ######################################## # 檢查資料表是否存在(資料表) ######################################## function chk_isTable($tbl_name="") { global $mysqli; if(!$tbl_name)return; $sql = "SHOW TABLES LIKE '{$tbl_name}'";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); if ($result->num_rows)return true; //欄位存在 return false;//欄位不存在 }
一、kind.php
<?php require_once 'head.php'; #定義常用變數 $TBL['name']="show_kind";//資料表名稱 $TBL['kind']="kind_prod";//分類 #整理傳入變數 $op = isset($_REQUEST['op'])?$_REQUEST['op']:""; $sn = isset($_REQUEST['sn'])?intval($_REQUEST['sn']):""; #程式流程 switch($op){ #新增記錄 case "op_insert": $sn=op_insert(); redirect_header("kind.php?op=op_show&sn={$sn}",3000,"新增資料成功!!"); exit; break; #更新記錄 case "op_update": $sn=op_update($sn); redirect_header("kind.php?op=op_show&sn={$sn}",3000,"更新資料成功!!"); exit; break; #刪除記錄 case "op_delete": op_delete($sn); redirect_header($_SESSION['CurrentUrl'],3000,"刪除記錄成功!!"); exit; break; #表單 case "op_form": op_form($sn); break; #顯示單筆 case "op_show": op_show($sn); break; #列表 default: # ---- 目前網址 ---- $_SESSION['CurrentUrl']=getCurrentUrl(); $op="op_list"; op_list(); break; } #將變數送至樣板引擎 #op $smarty->assign("op", $op); /* $WEB['theme_name'] = "admin"; WEB['title'] = "網站名稱"; $WEB['file_name'] = basename ($_SERVER['PHP_SELF']); */ #變數在head.php $smarty->assign("WEB", $WEB); #程式結尾 $smarty->display('theme.html'); #函數 ######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli,$TBL; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['enable'] = intval($_POST['enable']); //$_POST['sort'] = intval($_POST['sort']); $_POST['sort'] = get_max_sort_show_kind("sort",$TBL);//直接寫入最大值 # nav_home => 首頁的選單 $_POST['kind'] = $TBL['kind']; $sql = "insert into `{$TBL['name']}` (`title`, `enable`, `sort`,`kind`) VALUES ('{$_POST['title']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['kind']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 return $sn; } ######################################## # 更新記錄 ######################################## function op_update($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"更新記錄錯誤!!"); #資料過濾 $_POST['sn'] = intval($_POST['sn']); $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $sql = "update `{$TBL['name']}` set `title` = '{$_POST['title']}' , `enable` = '{$_POST['enable']}', `sort` = '{$_POST['sort']}' where sn='{$_POST['sn']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return $sn; } ############################################################################### # 刪除資料 ############################################################################### function op_delete($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!"); #檢查 $sql = "delete from `{$TBL['name']}` where `sn`='{$sn}'";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return; } ######################################## #取得單筆記錄 ######################################## function get_show_kind($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = intval($DBV['enable']); $DBV['target'] = intval($DBV['target']); return $DBV; } ######################################## # 表單 ######################################## function op_form($sn="") { global $mysqli,$smarty; #抓取預設值 if($sn) { #編輯 $DBV=get_show_kind($sn);//取得單筆記錄 $DBV['op'] = "op_update"; $DBV['form_title'] = "編輯類別"; //print_r($DBV);die(); }else { #新增 $DBV=array(); $DBV['op'] = "op_insert"; $DBV['form_title'] = "新增類別"; } //預設值設定 //標題 title (text)、網址 url (text)、是否外連 target (radio)、是否啟用 enable (radio)、排序 sort(text) $DBV['sn'] = (isset($DBV['sn'])) ? $DBV['sn'] : ""; $DBV['title'] = (isset($DBV['title'])) ? $DBV['title'] : ""; $DBV['enable'] = (isset($DBV['enable'])) ? $DBV['enable'] : "1"; $DBV['target'] = (isset($DBV['target'])) ? $DBV['target'] : "0"; $DBV['url'] = (isset($DBV['url'])) ? $DBV['url'] : ""; $DBV['sort'] = (isset($DBV['sort'])) ? $DBV['sort'] : ""; $smarty->assign("DBV", $DBV); return; } ######################################## # op_show ######################################## function op_show($sn="") { global $mysqli,$smarty,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); #取得單筆記錄,可以寫成函數 #sn ofsn kind title sort enable url target col_sn content $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}' and `kind`='{$TBL['kind']}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['url'] = htmlspecialchars($DBV['url'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = $DBV['enable'] ? "是":"<span style='color:red;'>否</span>"; $DBV['target'] = $DBV['target'] ? "是":"<span style='color:red;'>否</span>"; $smarty->assign("DBV", $DBV); return; } ######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` where `kind`='{$TBL['kind']}' order by `sort` ";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $rows=array(); while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $rows[]= $row; } $smarty->assign("DBV", $rows); return; }
二、樣板
{* 類別管理 表單 *} {if $WEB.file_name == "kind.php" and $op == "op_form"} <div class="container" style="margin-top:20px;"> <div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">{$DBV.form_title}</h3> </div> <div class="panel-body"> <form action="kind.php" method="post"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <input type="text" class="form-control" id="title " name="title" value="{$DBV.title}" placeholder="標題"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <input type='radio' name='enable' id='enable_1' value='1' {if $DBV.enable==1}checked{/if} > <label for='enable_1'>是</label> <input type='radio' name='enable' id='enable_0' value='0' {if $DBV.enable==0}checked{/if}> <label for='enable_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <input type="text" class="form-control" id="sort" name="sort" value="{$DBV.sort}" placeholder="排序"> </div> </div> </div> <!--用來控制程式流程--> <input type="hidden" name="op" value="{$DBV.op}"> <input type="hidden" name="sn" value="{$DBV.sn}"> <button type="submit" class="btn btn-default">送出</button> </form> </div> </div> </div> {/if} {* 類別管理 顯示單筆 *} {if $WEB.file_name == "kind.php" and $op == "op_show"} <div class="container" style="margin-top:20px;"> <div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> <button onclick="window.location.href='?op=op_form&sn={$DBV.sn}'" type="button" class="btn btn-success">編輯</button> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">顯示單筆</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <div class="form-control">{$DBV.title}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <div class="form-control">{$DBV.enable}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <div class="form-control">{$DBV.sort}</div> </div> </div> </div> </div> </div> </div> {/if} {* 類別管理 列表 *} {if $WEB.file_name == "kind.php" and $op == "op_list"} {literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='kind.php?op=op_delete&sn=' + sn; }); } </script> {/literal} <div class="container" style="margin-top:20px;"> <h2 class="text-center">類別管理</h2> <table class="table table-bordered table-hover list-table"> <thead> <tr class="active"> <th class="text-center col-md-8">標題</th> <th class="text-center col-md-1">排序</th> <th class="text-center col-md-1">啟用</th> <th class="text-center col-md-2"> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary btn-xs">新增</button> </th> </tr> </thead> <tbody> {foreach from=$DBV item=row} <tr> <td>{$row.title}</td> <td class="text-center">{$row.sort}</td> <td class="text-center">{$row.enable}</td> <td class="text-center"> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning btn-xs">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success btn-xs">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger btn-xs">刪除</button> </td> </tr> {/foreach} </tbody> </table> </div> {/if}
#檢查資料表(show_prod) if(!chk_isTable("show_prod")) go_update3();
######################################## # 建立資料表show_prod ######################################## function go_update3() { global $mysqli; $sql=" CREATE TABLE `show_prod` ( `sn` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'prod_sn', `kind` smallint(5) unsigned NOT NULL default 0 COMMENT '分類', `title` varchar(255) NOT NULL default '' COMMENT '名稱', `summary` text NOT NULL default '' COMMENT '摘要', `content` text NOT NULL default '' COMMENT '內容', `price` int(10) unsigned NOT NULL default 0 COMMENT '價格', `enable` enum('1','0') NOT NULL DEFAULT '1' COMMENT '狀態', `date` int(10) unsigned NOT NULL default 0 COMMENT '建立日期', `sort` smallint(5) unsigned NOT NULL default 0 COMMENT '排序', `counter` int(10) unsigned NOT NULL default 0 COMMENT '人氣', PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ";//die($sql); $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); return true; }
mk_dir(WEB_PATH."/uploads/prod");//商品圖
一、prod.php
<li><a href='prod.php'>商品管理</a></li>
二、修改
#定義常用變數 $TBL['name']="show_kind";//資料表名稱 $TBL['kind']="slider_home";//分類
=>
#定義常用變數 $TBL['name']="show_prod";//資料表名稱 $TBL['kind']="kind_prod";//分類
三、前台
$block_prod = get_block_prod();
get_block_prod()
https://www.ugm.com.tw/modules/tad_book3/page.php?tbdsn=227
{* 商品管理 列表 *} {if $WEB.file_name == "prod.php" and $op == "op_list"} {literal} <link rel="stylesheet" href="../class/sweet-alert/sweet-alert.css" type="text/css" /> <script src="../class/sweet-alert/sweet-alert.js" type="text/javascript"></script> <script type="text/javascript"> function op_delete_js(sn){ swal({ title: '確定要刪除此資料?', text: '相關資料通通都將會被移除!', type: 'warning', showCancelButton: 1, confirmButtonColor: '#DD6B55', confirmButtonText: '確定刪除!', closeOnConfirm: false , allowOutsideClick: true }, function(){ location.href='prod.php?op=op_delete&sn=' + sn; }); } </script> {/literal} <div class="container" style="margin-top:20px;"> <h2 class="text-center">商品管理</h2> <table class="table table-bordered table-hover list-table"> <thead> <tr class="active"> <th class="text-center col-md-1">縮圖</th> <th class="text-center col-md-1">日期</th> <th class="text-center col-md-3">標題</th> <th class="text-center col-md-2">價格</th> <th class="text-center col-md-1">排序</th> <th class="text-center col-md-1">人氣</th> <th class="text-center col-md-1">啟用</th> <th class="text-center col-md-2"> <button onclick="window.location.href='?op=op_form'" type="button" class="btn btn-primary btn-xs">新增</button> </th> </tr> </thead> <tbody> {foreach from=$rows item=row} <tr> <td>{if $row.file_name} <img src="{$row.file_name}" class="img-responsive">{/if}</td> <td>{$row.date}</td> <td>{$row.title}</td> <td class="text-right">{$row.price}</td> <td class="text-center">{$row.sort}</td> <td class="text-center">{$row.counter}</td> <td class="text-center">{$row.enable}</td> <td class="text-center"> <button onclick="window.location.href='?op=op_show&sn={$row.sn}'" type="button" class="btn btn-warning btn-xs">瀏覽</button> <button onclick="window.location.href='?op=op_form&sn={$row.sn}'" type="button" class="btn btn-success btn-xs">編輯</button> <button onclick="javascript:op_delete_js({$row.sn});" type="button" class="btn btn-danger btn-xs">刪除</button> </td> </tr> {/foreach} </tbody> </table> </div> {/if}
######################################## # 列表 ######################################## function op_list() { global $mysqli,$smarty,$TBL; #取得所有記錄 $sql = "select * from `{$TBL['name']}` order by `sort` desc";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $rows=array(); $col_name = "prod";//圖片資料表的關鍵字 while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $row['sort'] = intval($row['sort']); $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; $row['price'] = intval($row['price']); $row['counter'] = intval($row['counter']); $row['date'] = intval($row['date']);//日期是以時間戳記儲存 $row['date'] = date("Y-m-d",$row['date']);//http://www.w3school.com.cn/php/php_date.asp #取得圖片src $row['file_name'] = get_file_name_src($row['sn'],$col_name); $rows[]= $row; } $smarty->assign("rows", $rows); return; }
{* prod.php and op_form *} {if $WEB.file_name == "prod.php" and $op == "op_form"} <div class="container" style="margin-top:20px;"> <div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">{$DBV.form_title}</h3> </div> <div class="panel-body"> <form action="{$WEB.file_name}" method="post" enctype="multipart/form-data"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <input type="text" class="form-control" id="title " name="title" value="{$DBV.title}" placeholder="標題"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <input type='radio' name='enable' id='enable_1' value='1' {if $DBV.enable==1}checked{/if} > <label for='enable_1'>是</label> <input type='radio' name='enable' id='enable_0' value='0' {if $DBV.enable==0}checked{/if}> <label for='enable_0'>否</label> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <input type="text" class="form-control" id="sort" name="sort" value="{$DBV.sort}" placeholder="排序"> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label>類別</label> <select name="kind" class="form-control" size="1"> <{$DBV.kind_option}> </select> </div> </div> <script src="{$smarty.const.WEB_URL}/class/My97DatePicker/WdatePicker.js" type="text/javascript"></script> <div class="col-md-3"> <div class="form-group"> <label>日期</label> {$DBV.date} </div> </div> <div class="col-md-3"> <div class="form-group"> <label>價格</label> <input type="text" class="form-control" id="price" name="price" value="{$DBV.price}" placeholder="價格"> </div> </div> </div> <!-- 摘要--> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>摘要</label> <textarea class="form-control" rows="5" id="summary" name="summary">{$DBV.summary}</textarea> </div> </div> </div> <script src="{$smarty.const.WEB_URL}/class/ckeditor/ckeditor.js"></script> <!-- 內容--> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>內容</label> <textarea class="form-control" rows="5" id="content" name="content">{$DBV.content}</textarea> </div> </div> </div> <script> CKEDITOR.replace( 'content' ); </script> <div class="row"> <div class="col-md-9"> <div class="form-group"> <label>上傳圖片</label> <input name='file' type="file" id="file" class="form-control" accept="image/*" > </div> </div> {if $DBV.file_name} <div class="col-md-3"> <img src="{$DBV.file_name}" class="img-responsive" /> </div> {/if} </div> <!--用來控制程式流程--> <input type="hidden" name="op" value="{$DBV.op}"> <input type="hidden" name="sn" value="{$DBV.sn}"> <button type="submit" class="btn btn-default">送出</button> </form> </div> </div> </div> {/if}
######################################## # 表單 ######################################## function op_form($sn="") { global $mysqli,$smarty; #抓取預設值 if($sn) { #編輯 $DBV=get_show_prod($sn);//取得單筆記錄 $DBV['op'] = "op_update"; $DBV['form_title'] = "編輯商品"; //print_r($DBV);die(); }else { #新增 $DBV=array(); $DBV['op'] = "op_insert"; $DBV['form_title'] = "新增商品"; } //預設值設定 $DBV['sn'] = (isset($DBV['sn'])) ? $DBV['sn'] : ""; $DBV['title'] = (isset($DBV['title'])) ? $DBV['title'] : ""; $DBV['enable'] = (isset($DBV['enable'])) ? $DBV['enable'] : "1"; $DBV['sort'] = (isset($DBV['sort'])) ? $DBV['sort'] : ""; #商品類別 $DBV['kind'] = (isset($DBV['kind'])) ? $DBV['kind'] : ""; $DBV['kind_option'] = get_kind_prod_option($DBV['kind']); #日期 $DBV['date'] = (isset($DBV['date'])) ? date("Y-m-d H:i:s" , $DBV['date']) : date("Y-m-d H:i:s"); $DBV['date'] = "<input type='text' name='date' id='date' class='form-control' value='{$DBV['date']}' onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss' , startDate:'%y-%M-%d %H:%m:%s'})\">"; $DBV['price'] = (isset($DBV['price'])) ? $DBV['price'] : ""; $DBV['summary'] = (isset($DBV['summary'])) ? $DBV['summary'] : ""; $DBV['content'] = (isset($DBV['content'])) ? $DBV['content'] : ""; #圖片src $DBV['file_name'] = (isset($DBV['file_name'])) ? $DBV['file_name'] : ""; $smarty->assign("DBV", $DBV); return; }
######################################## #取得單筆商品記錄 ######################################## function get_show_prod($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}'";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = intval($DBV['enable']); $DBV['kind'] = intval($DBV['kind']); $DBV['price'] = intval($DBV['price']); $DBV['date'] = intval($DBV['date']); $DBV['counter'] = intval($DBV['counter']); $DBV['summary'] = htmlspecialchars($DBV['summary'], ENT_QUOTES); // 轉換雙引號和單引號 #取得圖片src $col_name="prod"; $DBV['file_name'] = get_file_name_src($DBV['sn'],$col_name); return $DBV; }
######################################## # 得到商品類別選項 ######################################## function get_kind_prod_option($kind="") { global $mysqli,$smarty,$TBL; $sql = "select sn,title from `show_kind` where `kind`='{$TBL['kind']}' and `enable`='1' "; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $options=""; while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 $selected = ($kind == $row['sn'])?" selected":""; $options .="<option value='{$row['sn']}'{$selected}>{$row['title']}</option>\n"; } return $options; }
######################################## # 新增記錄 ######################################## function op_insert() { global $mysqli,$TBL; #資料過濾 #http://php.net/manual/en/mysqli.real-escape-string.php $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['enable'] = intval($_POST['enable']); //$_POST['sort'] = intval($_POST['sort']); $_POST['sort'] = get_max_sort_show_prod("sort",$TBL);//直接寫入最大值 $_POST['kind'] = intval($_POST['kind']); $_POST['date'] = $mysqli->real_escape_string($_POST['date']); $_POST['date'] = strtotime($_POST['date']);//轉成時間戳記 $_POST['price'] = intval($_POST['price']); $_POST['summary'] = $mysqli->real_escape_string($_POST['summary']); $_POST['content'] = $mysqli->real_escape_string($_POST['content']); $sql = "insert into `{$TBL['name']}` (`title`, `enable`, `sort`,`kind`,`date`,`price`,`summary`,`content`) VALUES ('{$_POST['title']}', '{$_POST['enable']}', '{$_POST['sort']}', '{$_POST['kind']}', '{$_POST['date']}', '{$_POST['price']}', '{$_POST['summary']}', '{$_POST['content']}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $sn=$mysqli->insert_id;//傳回insert 指令所產生之流水號 /* $_FILES['file']['name']:上傳檔案原始名稱。 $_FILES['file']['type']:檔案的 MIME 類型,例如“image/gif”。 $_FILES['file']['size']:已上傳檔案的大小,單位為bytes。 $_FILES['file']['tmp_name']:檔案被上傳後的臨時檔案名。 $_FILES['file']['error']:和該檔案上傳相關的錯誤代碼。 */ if($_FILES['file'] and !$_FILES['file']['error']) { $col_name="prod";//商品圖的關鍵字 prod $col_sn=$sn;//相關流水號 $sort=1;//排序 $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//取得副檔名 $ext = strtolower($ext); //轉小寫 $sub_dir="/prod";//儲存位置 $file_name="prod_".$col_sn."_".$sort.".".$ext;//檔名 if($ext == "png" or $ext == "gif" or $ext == "jpg" or $ext == "jpeg" or $ext == "jpe") { $kind="img"; }else { $kind="file"; } #寫入資料表 show_files $sql = "insert into `show_files` (`col_name`, `col_sn`, `sort`, `kind`,`file_name`,`file_type`,`file_size`,`description`,`sub_dir`) VALUES ('{$col_name}', '{$col_sn}', '{$sort}', '{$kind}', '{$file_name}', '{$_FILES['file']['type']}','{$_FILES['file']['size']}', '{$_POST['title']}', '{$sub_dir}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $new_file= WEB_PATH."/uploads".$sub_dir."/".$file_name; #移動檔案 move_uploaded_file($_FILES['file']['tmp_name'] , $new_file); } return $sn; }
##################################################################################### # 自動取得商品檔(排序欄位,資料表)的最新排序 # get_max_sort_show_prod($col,$TBL) # (排序欄位,資料表)# ##################################################################################### if(!function_exists("get_max_sort_show_prod")){ function get_max_sort_show_prod($col="sort",$TBL=""){ global $mysqli; if(empty($TBL))return; $sql = "select max({$col}) from `{$TBL['name']}`"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); list($sort)=$result->fetch_row(); return ++$sort; } }
{* 商品管理 顯示單筆 *} {if $WEB.file_name == "prod.php" and $op == "op_show"} <div class="container" style="margin-top:20px;"> <div style="margin:10px 0;"> <button onclick="window.location.href='{$smarty.session.CurrentUrl}'" type="button" class="btn btn-warning">返回</button> <button onclick="window.location.href='?op=op_form&sn={$DBV.sn}'" type="button" class="btn btn-success">編輯</button> </div> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">顯示單筆</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <div class="form-control">{$DBV.title}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label style="display:block;">啟用狀態</label> <div class="form-control">{$DBV.enable}</div> </div> </div> <div class="col-md-2"> <div class="form-group"> <label>排序</label> <div class="form-control">{$DBV.sort}</div> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="form-group"> <label>類別</label> <div class="form-control">{$DBV['kind']}</div> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>日期</label> <div class="form-control">{$DBV['date']}</div> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>價格</label> <div class="form-control">{$DBV['price']}</div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>摘要</label> <div class="alert alert-success">{$DBV['summary']}</div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <label>內容</label> <div class="alert alert-info">{$DBV['content']}</div> </div> </div> <div class="row"> {if $DBV.file_name} <div class="col-md-3"> <img src="{$DBV['file_name']}" alt="{$DBV.title}" class="img-responsive"> </div> {/if} </div> </div> </div> </div> {/if}
######################################## # op_show ######################################## function op_show($sn="") { global $mysqli,$smarty,$TBL; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); #取得單筆記錄,可以寫成函數 #sn ofsn kind title sort enable url target col_sn content $sql = "select * from `{$TBL['name']}` where `sn`='{$sn}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['sn'] = intval($DBV['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['sort'] = intval($DBV['sort']); $DBV['enable'] = $DBV['enable'] ? "是":"<span style='color:red;'>否</span>"; $DBV['date'] = intval($DBV['date']); $DBV['date'] = date("Y-m-d H:i:s",$DBV['date']);//格式化日期 $DBV['kind'] = intval($DBV['kind']); $DBV['kind'] = get_show_kind_title($DBV['kind']);//取得類別標題 //取得類標題 $DBV['summary'] = htmlspecialchars($DBV['summary'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['summary'] = nl2br($DBV['summary']); //$DBV['content'] = ($DBV['content'], ENT_QUOTES); // 轉換雙引號和單引號 $DBV['content'] = $DBV['content']; #取得圖片src $col_name="prod"; $DBV['file_name'] = get_file_name_src($DBV['sn'],$col_name); $smarty->assign("DBV", $DBV); return; }
######################################## #取得類別標題 ######################################## function get_show_kind_title($sn="") { global $mysqli; if(!$sn)redirect_header("index.php",3000,"查詢選單資料錯誤!!"); $sql = "select title from `show_kind` where `sn`='{$sn}'"; //$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $DBV = $result->fetch_assoc(); #過濾撈出資料 $DBV['title'] = htmlspecialchars($DBV['title'], ENT_QUOTES); // 轉換雙引號和單引號 return $DBV['title']; }
######################################## # 更新記錄 ######################################## function op_update($sn="") { global $mysqli,$TBL; if(!$sn)redirect_header("index.php",3000,"更新記錄錯誤!!"); #資料過濾 $_POST['sn'] = intval($_POST['sn']); $_POST['title'] = $mysqli->real_escape_string($_POST['title']); $_POST['enable'] = intval($_POST['enable']); $_POST['sort'] = intval($_POST['sort']); $_POST['kind'] = intval($_POST['kind']); $_POST['date'] = $mysqli->real_escape_string($_POST['date']); $_POST['date'] = strtotime($_POST['date']);//將日期轉成時間戳記 $_POST['price'] = intval($_POST['price']); $_POST['summary'] = $mysqli->real_escape_string($_POST['summary']); $_POST['content'] = $mysqli->real_escape_string($_POST['content']); $sql = "update `{$TBL['name']}` set `title` = '{$_POST['title']}' , `enable` = '{$_POST['enable']}', `sort` = '{$_POST['sort']}', `kind` = '{$_POST['kind']}', `date` = '{$_POST['date']}', `price` = '{$_POST['price']}', `summary` = '{$_POST['summary']}', `content` = '{$_POST['content']}' where sn='{$_POST['sn']}'"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); /* $_FILES['file']['name']:上傳檔案原始名稱。 $_FILES['file']['type']:檔案的 MIME 類型,例如“image/gif”。 $_FILES['file']['size']:已上傳檔案的大小,單位為bytes。 $_FILES['file']['tmp_name']:檔案被上傳後的臨時檔案名。 $_FILES['file']['error']:和該檔案上傳相關的錯誤代碼。 */ if($_FILES['file'] and !$_FILES['file']['error']) { #刪除舊檔(資料表、實體檔案) $col_name="prod";//商品圖的關鍵字 prod delete_file_name($sn,$col_name); #----------------------- //$col_name=$TBL['kind'];//輪播圖的關鍵字 slider_home $col_sn=$sn;//相關流水號 $sort=1;//排序 $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//取得副檔名 $ext = strtolower($ext); //轉小寫 $sub_dir="/prod";//儲存位置 $file_name="prod_".$col_sn."_".$sort.".".$ext;//檔名 if($ext == "png" or $ext == "gif" or $ext == "jpg" or $ext == "jpeg" or $ext == "jpe") { $kind="img"; }else { $kind="file"; } #寫入資料表 show_files $sql = "insert into `show_files` (`col_name`, `col_sn`, `sort`, `kind`,`file_name`,`file_type`,`file_size`,`description`,`sub_dir`) VALUES ('{$col_name}', '{$col_sn}', '{$sort}', '{$kind}', '{$file_name}', '{$_FILES['file']['type']}','{$_FILES['file']['size']}', '{$_POST['title']}', '{$sub_dir}')"; $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $new_file= WEB_PATH."/uploads".$sub_dir."/".$file_name; #移動檔案 move_uploaded_file($_FILES['file']['tmp_name'] , $new_file); } return $sn; }
###############################################################################
# 刪除資料
###############################################################################
function op_delete($sn="")
{
global $mysqli,$TBL;
if(!$sn)redirect_header("index.php",3000,"刪除記錄錯誤!!");
#刪除舊檔(資料表、實體檔案)
$col_name="prod";
delete_file_name($sn,$col_name);
#刪除 show_kind
$sql = "delete
from `{$TBL['name']}`
where `sn`='{$sn}'";//die($sql);
$mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate));
return;
}
######################################## # 取得商品列表 ######################################## function get_block_prod() { global $mysqli,$smarty; $TBL['name'] = "show_prod"; #取得所有記錄 $sql = "select * from `{$TBL['name']}` order by `sort` desc";//die($sql); $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $rows=array(); $col_name = "prod";//圖片資料表的關鍵字 while($row = $result->fetch_assoc()) { #過濾撈出資料 $row['sn'] = intval($row['sn']); //http://www.w3school.com.cn/php/func_string_htmlspecialchars.asp // $row['title'] = htmlspecialchars($row['title'], ENT_QUOTES); // 轉換雙引號和單引號 // $row['sort'] = intval($row['sort']); // $row['enable'] = $row['enable'] ? "是":"<span style='color:red;'>否</span>"; // $row['price'] = intval($row['price']); // $row['counter'] = intval($row['counter']); // $row['date'] = intval($row['date']);//日期是以時間戳記儲存 // $row['date'] = date("Y-m-d",$row['date']);//http://www.w3school.com.cn/php/php_date.asp #取得圖片src $row['file_name'] = get_file_name_src($row['sn'],$col_name); $rows[]= $row; } $smarty->assign("block_prod", $rows); return; }
{* 在index.php *} {if $WEB.file_name == "index.php"} <script src="{$smarty.const.WEB_URL}/class/backstretch/jquery.backstretch.min.js"></script> {$backstretch_js} <style> .top-content{ height:600px; } </style> <div class="top-content"></div> <div class="container" style="margin-top:40px;"> <div class="row"> {foreach from=$block_prod item=row} <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="{$row.file_name}" > </a> </div> {/foreach} </div> </div> {/if}
$DBV['date'] = (isset($DBV['date'])) ? date("Y-m-d H:i:s" , $DBV['date']) : date("Y-m-d H:i:s");
$DBV['date'] = "<input type='text' name='date' id='date' class='form-control' value='{$DBV['date']}' onClick=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss' , startDate:'%y-%M-%d %H:%m:%s'})\">";
<script src="{$smarty.const.WEB_URL}/class/My97DatePicker/WdatePicker.js" type="text/javascript"></script> <div class="col-md-3"> <div class="form-group"> <label>日期</label> {$DBV.date} </div> </div>
<script src="{$smarty.const.WEB_URL}/class/ckeditor/ckeditor.js"></script> <!-- 內容--> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label>內容</label> <textarea class="form-control" rows="5" id="content" name="content">{$DBV.content}</textarea> </div> </div> </div> <script> CKEDITOR.replace( 'content' ); </script>
<script src="{$smarty.const.WEB_URL}/class/jQuery-Validation-Engine/js/languages/jquery.validationEngine-zh_TW.js" type="text/javascript" charset="utf-8"></script> <script src="{$smarty.const.WEB_URL}/class/jQuery-Validation-Engine/js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" href="{$smarty.const.WEB_URL}/class/jQuery-Validation-Engine/css/validationEngine.jquery.css" type="text/css"/> <script type="text/javascript"> $(document).ready(function() { $("#myForm").validationEngine(); }); </script>
<form action="prod.php" id="myForm" method="post" enctype="multipart/form-data"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>標題</label> <input type="text" class="form-control validate[required]" id="title" name="title" value="{$DBV.title}" placeholder="標題"> </div> </div>
<input type="text" name="num" id="num" class="validate[required, min[1], max[10]]">
(1) equals[field.id]:等於某欄位
(2) min[float]:最小值、max[float]:最大值
(3) minSize[integer]:最小字數、maxSize[integer]:最大字數
(4) past[NOW or a date]:日期是否小於指定日期
(5) future[NOW or a date]:日期是否大於指定日期
(6) minCheckbox[integer]:至少選幾個、maxCheckbox[integer]:最多選幾個
(7) custom[格式]:驗證各種輸入內容
<input type="text" name="mail" id="mail" class="validate[required , custom[email]]">
a. phone:電話
b. url:網址
c. email:Email
d. date:日期 YYYY-MM-DD
e. number:數字,如:-143.22 or .77 but also +234,23
f. integer:整數,如:-635 +2201 738
g. ipv4:IP,如:127.0.0.1
h. onlyNumber:僅數字、onlyNumberSp:僅數字及空白
i. onlyLetter:僅字元、onlyLetterSp:僅字元及空白
j. onlyLetterNumber:僅字元和數字,無空白
k. onChineseSp:只能用中文字及空白,不能用特殊符號、數字、英文
l. onChinese:只能用中文字,不能用特殊符號、數字、英文及空白
{* 類別管理 列表 *} {if $WEB.file_name == "kind.php" and $op == "op_list"}
加入
<link rel="stylesheet" href="../class/jQueryUi/jquery-ui.css" type="text/css" /> <script src="../class/jQueryUi/jquery-ui.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { //排序 $('#sort').sortable(); }); </script>
include_once WEB_PATH."/class/PageBar.php"; $counter = 20 ;//每頁顯示幾筆資料 $pages = 10 ; //分頁工具呈現幾頁 $PageBar = getPageBar($sql, $counter, $pages); $total = $PageBar['total'];//得到總筆數 $sql = $PageBar['sql'];//重新得到sql語法 $bar = ($total > $counter)?$PageBar['bar']:"";//顯示總筆數 > 每頁顯示幾筆資料 ,則出現分頁 $smarty->assign("bar", $bar);//將分頁送至樣板 $smarty->assign("total", $total);//將總筆數送至樣板
{$bar}
<?php defined('WEB_PATH') || die("WEB_PATH root path not defined"); /* 共用函數區,前、後台共用 */ ############################################################################### # 訊息通知 ############################################################################### function redirect_header($url="", $time = 3000, $message = '已轉向!!') { $_SESSION['redirect']=" $(document).ready(function(){ $.jGrowl('{$message}', { life:{$time} , position: 'center', speed: 'slow' }); }); "; header("location:{$url}"); exit; } ############################################################################### # 取得目前網址 ############################################################################### if(!function_exists("getCurrentUrl")){ function getCurrentUrl(){ global $_SERVER; $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')=== FALSE ? 'http' : 'https'; $host = $_SERVER['HTTP_HOST']; $script = $_SERVER['SCRIPT_NAME']; $params = $_SERVER['QUERY_STRING']?'?' . $_SERVER['QUERY_STRING']:""; $currentUrl = $protocol . '://' . $host . $script . $params; return $currentUrl;; } } ##################################################################################### # 自動取得(排序欄位,資料表)的最新排序 # get_max_sort_show_kind($col,$TBL) # (排序欄位,資料表)# ##################################################################################### if(!function_exists("get_max_sort_show_kind")){ function get_max_sort_show_kind($col="sort",$TBL=""){ global $mysqli; if(empty($col) or empty($TBL))return; $sql = "select max({$col}) from `{$TBL['name']}` where kind='{$TBL['kind']}'"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); list($sort)=$result->fetch_row(); return ++$sort; } } ##################################################################################### # 建立目錄 ##################################################################################### if(!function_exists("mk_dir")){ function mk_dir($dir = "") { #若無目錄名稱秀出警告訊息 if (empty($dir)) { return; } #若目錄不存在的話建立目錄 if (!is_dir($dir)) { umask(000); //若建立失敗秀出警告訊息 mkdir($dir, 0777); } } } ######################################## # #取得圖片 ######################################## function get_file_name($col_sn,$col_name) { global $mysqli; if(!$col_sn or !$col_name)return; # $sql = "select * from `show_files` where `col_sn`='{$col_sn}' and `col_name`='{$col_name}' order by sort"; $result = $mysqli->query($sql) or die(printf("Error: %s <br>".$sql, $mysqli->sqlstate)); $row = $result->fetch_assoc(); #---------------- return $row; } ######################################## # #取得圖片src ######################################## function get_file_name_src($col_sn,$col_name) { if(!$col_sn or !$col_name)return; $row = get_file_name($col_sn,$col_name); #---------------- #圖片檔src $file_name = $row['file_name'] ? WEB_URL."/uploads".$row['sub_dir']."/".$row['file_name']:""; return $file_name; }
<link rel="stylesheet" href="css/superslides.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="javascripts/jquery.easing.1.3.js"></script> <script src="javascripts/jquery.animate-enhanced.min.js"></script> <script src="javascripts/jquery.superslides.js" type="text/javascript" charset="utf-8"></script>
<script> $('#slides').superslides({ animation: 'fade' }); </script>
<div id="slides"> <div class="slides-container"> <img src="images/people.jpeg" alt="Cinelli"> <img src="images/surly.jpeg" width="1024" height="682" alt="Surly"> <img src="images/cinelli-front.jpeg" width="1024" height="683" alt="Cinelli"> <img src="images/affinity.jpeg" width="1024" height="685" alt="Affinity"> </div> <nav class="slides-navigation"> <a href="#" class="next">Next</a> <a href="#" class="prev">Previous</a> </nav> </div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> <script type="text/javascript" src="gmaps.js"></script>
<script type="text/javascript"> var map; $(document).ready(function(){ map = new GMaps({ div: '#map', lat: 23.0097244,//緯度 lng: 120.2693//經度 }); map.addMarker({ lat: 23.0097244, lng: 120.2693, title: '育將電腦工作室',//標題,23.0097244,120.2670898 infoWindow: { content: "<div style='color:black;'>台南市永康區大灣路158號<br>育將電腦工作室</div>"//視窗 } }); map.drawOverlay({ lat: 23.0097244, lng: 120.2693, content: "<div style='color:black;'>育將電腦工作室</div>" }); }); </script>
<div id="map" style="height:300px;width:50%;"></div>
<!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Google Maps</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js 讓 IE8 支援 HTML5 元素與媒體查詢 --> <!-- 警告:Respond.js 無法在 file:// 協定下運作 --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery (Bootstrap 所有外掛均需要使用)--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- 依需要參考已編譯外掛版本(如下),或各自獨立的外掛版本 --> <script src="js/bootstrap.min.js"></script> </head> <body> <!--導覽列 start--> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">首頁</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="index.html">首頁</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav><!-- /.nav --> <div class="container"> <div> <!-- 引入js檔案結束 --> <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=API KEY"> </script> <script> function initialize() { //設定一個經緯度給latlng var latlng = new google.maps.LatLng(23.0097244,120.2693); //建立一個名叫 myOptions的地圖設定參數,縮放層級是8,中央點的座標是latlng //地圖的樣式是 ROADMAP var myOptions = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; //在網頁中找到一個id值為map_canvas的DOM,並產出地圖,這個地圖的參數為myOptions。 var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); //這裡要產生標記 //標記位置是myLatLng var myLatLng = new google.maps.LatLng(23.0097244,120.2693); //在地圖map產生第一個標記,標記的位置是myLatLng,而且標記不能移動draggable:true,。 var Marker1 = new google.maps.Marker({ draggable:false, position: myLatLng, map: map }); } </script> <script> $(function(){ initialize(); }); </script> </div> </div> <!--這個區塊一定要給高度與寬度--> <div id="map_canvas" style="width:100%; height:500px;"></div> </body> </html>