我建了兩個頁面,text.html是一個靜態表單頁面,在text.html的表單中輸入資料,然後db.php獲得表單中的資料,並將資料插入資料庫輸出來顯示到頁面上。下面直接看代碼,需要說明的地方就直接寫在注釋裡面了。
text.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml"><br /><head><br /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><br /><title>表單頁</title><br /></head></p><p><body></p><p><form method=post action="db.php" ><br /><p> 產 品ID:<input type="text" name="proid" width="100px" /></p><br /><p> 產品名稱:<input type="text" name="proname" width="100px" /></p><br /><p> 產品描述:<input type="text" name="prodes" width="100px" /></p><br /><input type="submit" value="提交" /></p><p></body><br /></html>
db.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml"><br /><head><br /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><br /><title>資料庫連接</title><br /></head><br /><body><br /><?php<br />error_reporting(0);//這句話是為了避免警告 Notice: Undefined index: proid in……<br />$DBServer = "localhost";//定義資料庫伺服器<br />$DBUser = "sa";//定義資料庫使用者名稱<br />$DBPass = "123";//定義資料庫訪問密碼</p><p>$conn = mysql_connect($DBServer,$DBUser,$DBPass);</p><p>//下面注釋部分 測試資料庫是否串連成功的代碼<br />/* if(!$conn)<br /> die('Could not connect: ' . mysql_error());<br /> else echo '<p>串連成功</p>'; */</p><p>mysql_select_db("sa", $conn);<br />mysql_query("SET names utf8");//這裡是為了確保頁面顯示資料和資料庫使用同樣的編碼方式,如沒有這句有可能導致資料輸出和輸入為問號</p><p>mysql_query("INSERT INTO product (PRO_ID, PRO_NAME,PRO_DESCRIPTION)<br />VALUES ('$_POST[proid]','$_POST[proname]' ,'$_POST[prodes]')");//插入資料,其中被傳入的3個參數為text.php中表單輸入的參數,這裡擴充瞭解一下$_POST,$_GET,$_REQUST的區別</p><p>$sql = "select * from product";//資料庫查詢<br />$result = mysql_query($sql);</p><p>echo "<TABLE border=1>//echo裡面是可以寫html代碼的,包括style都是可以寫的<br /> <TR><br /> <TD>編號</TD><br /> <TD>名稱</TD><br /> <TD>詳細資料</TD><br /> </TR>";</p><p> while($row=mysql_fetch_array($result)){//輸出資料<br /> echo "<TR><br /> <TD> $row[PRO_ID] </TD><br /> <TD> $row[PRO_NAME] </TD><br /> <TD> $row[PRO_DESCRIPTION] </TD><br /> </TR>";<br /> }<br /> echo "</TABLE>";</p><p>mysql_close($conn);//關閉串連,看到網上有人說不需要關閉,php可以自己關閉,我決定還是先關閉比較好,畢竟初學,養成良好的習慣<br /></body><br /></html>