通過上一篇文章已經了解到如何利用Ajax和PHP對數據庫進行數據讀取,這樣可以動態的獲取到數據庫的最新數據。本篇則繼續介紹通過表單(Form)向數據庫中寫入數據。
談到Form就涉及到一個發送請求方式問題(GET和POST),對于GET和POST的使用和區別在本文就不詳細說明了,一般對于Web開發由于POST傳值為隱式且傳輸數據量較大所以比較常用。在本例中對functions.js進行下修改,將創建XMLHttp對象程序創建為一個函數processajax。
在下圖中當點擊“Submit”按鈕后會激發submitform函數(functions.js),在該函數中會通過getformvalues函數檢查Form內容是否都填寫完畢,否則提示哪項未填寫。當檢查通過后會調用process_task.php程序,它會將Form值寫入數據庫。
<?php
require_once ("dbconnector.php");
opendatabase();
//對數據預處理
$yourname = strip_tags (mysql_real_escape_string ($_POST['yourname']));
$yourtask = strip_tags (mysql_real_escape_string ($_POST['yourtask']));
$thedate = strip_tags (mysql_real_escape_string ($_POST['thedate']));
//創建Insert語句
$myquery = "INSERT INTO task (name, thedate, description) VALUES ('$yourname','$thedate','$yourtask')";
//執行SQL語句
if (!mysql_query ($myquery)){
header ("Location: theform.php?message=There was a problem with the entry.");
exit;
}
//返回成功信息
header ("Location: theform.php?message=Success");
?>
源碼:Sample5.rar
作者博客:http://www.cnblogs.com/gnielee/