模組基本內容-使用表單與資料庫

日期 2010年09月02日 21:57:17 | 新聞類別: 模組開發

原始出處 http://www.xoops.org/modules/mediawiki/index.php/Basic_content_of_a_module


 

使用表單與資料庫

讓我們在index.php 內建立一個簡單的表單吧

<?php

 // Tutorial

 // Created by KaotiK

 require('../../mainfile.php');

 require(XOOPS_ROOT_PATH.'/header.php');

 ?>

 <form name="tutorial_form" method="post" action="index.php">

 <table width="400" border="0">

 <tr>

 <td align="right">Name</td>

 <td><input type="text" name="name"></td>

 </tr><tr>

 <td align="right">Address</td>

 <td><input type="text" name="address"></td>

 </tr><tr>

 <td align="right">Telephone</td>

 <td><input type="text" name="tel"></td>

 </tr><tr>

 <td align="right">Email</td>

 <td><input type="text" name="email"></td>

 </tr><tr>

 <td> </td>

 <td><input type="submit" name="submit" value="submit"></td>

 </tr>

 </table>

 </form>

 <?php

 require(XOOPS_ROOT_PATH.'/footer.php');

 ?>

當你點選主選單的tutorial 你會看到一個有name,address,telephone,email 與一個submit 按鈕的表單。點選submit 按鈕會將畫面帶回index.php 但是不會作任何動作。
加入以下的程式碼:

<?php

// Tutorial

// Created by KaotiK

require('../../mainfile.php');

require(XOOPS_ROOT_PATH.'/header.php');

 

if (isset($_POST['submit'])){

echo 'my name is: '. $_POST['name'];

}

?>


我只有將程式碼的上半部放入以保持文件頁面的精簡。在你的index.php 檔案中應該要有全部的程式碼。

現在當你點選submit 後你會看到一段字"my name is: "與你的名字。讓我解釋一下發生了什麼事情。php 的指令if 是一個選擇條件式。如果條件式的結果是TRUE 時則執行某些指令。在這個範例中如果有點選表單按鈕則執行列印指令。submit 按鈕是$_POST['submit'] 而'submit'是按鈕的名稱,為了檢查他是否存在,我使用isset,如果回傳TRUE 則表示按鈕存在而FALSE 則表示不存在。
現在不填任何資料點選submit。你會看到畫面仍然顯示"my name is: "而沒有名字。讓我們產生一個當使用者沒有填入名字時的錯誤訊息。

<?php

// Tutorial

// Created by KaotiK

require('../../mainfile.php');

require(XOOPS_ROOT_PATH.'/header.php');

 

if (isset($_POST['submit'])){

if (empty($_POST['name'])){

echo 'please fill in a name';

} else {

echo 'my name is: '. $_POST['name'];

}

}

?>

現在當不輸入姓名按下submit 按鈕時就會出現錯誤訊息。你可以注意到我在IF 裡面用了另外一個IF。這個意思是:如果表單中"name"欄位是空白的話則顯示'please fill in a name',如果有值的話(else)則顯示'my name is: '. $_POST['name']





本篇新聞來自:XOOPS Site
https://www.xoops.org.tw

本篇新聞的連結網址是:
https://www.xoops.org.tw/modules/news/article.php?storyid=53