Chapter 4. HTML From

การจัดการ HTML Form

             

             จากบทที่ผ่านมาเราได้ทดสอบเขียน PHP กันแล้ว แต่เขียนในรูปของ ภาษา PHP อย่างเดียว ยังมิได้เขียนร่วมกับ HTML Form ซึ่งนับว่าเป็นหัวใจสำคัญของ CGI (Command Gate Way Interface)  ก่อนเริ่มเขียน ผมขอแนะนำให้คนที่ยังไม่เคยเขียนหรือไม่เข้าใจเกี่ยวคำสั่ง Form ของ html ต้องกลับไปทบทวนเขียนให้คล่องเสียก่อน เพราะถือว่า Form เป็นประตูด่านแรกที่จะนำคุณเข้าสู้ CGI (Command Gate Way Interface) และเชื่อมต่อ PHP เรามาเริ่มกันเลย

 รูปแบบการแทรก Script PHP

<?

Command PHP

?>

วิธีทำ
1. ติดตั้ง Webserver และ PHP Complier ในเครื่องของคุณตามขั้นตอนที่ได้กล่าวไปแล้ว
2. เขียน File Form ชื่อ order.html ตามตัวอย่างข้างล่าง
3. เขียน File PHP ชื่อ order.php3 ตามตัวอย่างข้างล่าง
4. ทดสอบโดยนำ order.html ไปไว้ที่ Subdirectory c:\httpd\htdocs ( ขอพูดเฉพาะ windows 95/98 เพราะ Unix พี่ๆ  Admin คงเข้าใจกันดี) order.php3 ไปไว้ที่ Subdirectory c:\httpd\cgi-php\

5. ไปที่ Browser พิมพ์ http://localhost/order.html

ตัวอย่าง file html

order.html

<html>
<
head><title>ThaiWBI ShoppingForm สั่งซื้อสิ้นค้า</title>
<
/head>

<body>

<form method="POST" action="order.php3">

<center><h3>ThaiWBI Shopping</h3><br>
<h1>Form สั่งซื้อสิ้นค้า</h1><center>

Name <input type="text" name="name"><br>
Email<input type="text" name="email"><p>

ต้องการสั่งซื้อหนังสือ

<input type="checkbox" name="book1" value="Database On Web">Database On Web<br>
<input type="checkbox" name="book2" value="CGI PHP">CGI PHP<p>

<input type="submit" value="Order Now"><input type="reset" value="Reset">

</form>

</body>
<
/html>

 

ตัวอย่าง file php

order.php3

<html>
<
head><title>Form สั่งซื้องสิ้นค่า</title>
<
/head>

<?

print "คุณ $name <br> ";
print "
Email $email <br>";

print "สิ้นค่ามี่คุณต้องการสั่ง <br>";
print "
$book1<br>";
print "
$book2<br>";

?>

</body>

</html>

ทดลอง Run

html_from.gif (21890 bytes)

ผลลัพธ์

             out_php.gif (4685 bytes)

คำอธิบาย

      ใน file order.html เราได้กำหนดตัวแปรไว้ ดังนี้
$name = ชื่อผู้สั่งสินค้า
$email = email ของผู้สั่งสินค้า
$book1= สินค้าหนังสือ Database On Web
$book2= สินค้าหนังสือ CGI PHP

      ใน file order.php3 ได้กำหนดตัวแปรเช่นเดียวกับ order.html

      เมื่อ order.html ส่งตัวแปรทั้งหมดที่ถูกเลือกและถูกใส่ข้อมูลลงไป จากนั้น order.php3 ก็จะรับค่าตัวแปร และแสดงผลออกทางจอภาพ


Copy right Passkorn Roungrong 2000