In this tutorial, we will create a guestbook in PHP using AJAX. The records will be stored in the database. The table will contain the following information: sender's name, email address, IP address and date-time of the last entry. jQuery will be used (to implement AJAX). A simple spam protection will also be implemented - you can post no more than one entry every 10 minutes.
Step 1: SQL
For our application to work, we need to create a table:
CREATE TABLE IF NOT EXISTS `s178_guestbook` (`id` int(10) unsigned NOT NULL auto_increment, `name` varchar(255) default "", `email` varchar(255) default "", `description` varchar(255) default "", `when` int(11) NOT NULL default "0", `ip` varchar(20) default NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Step 2 PHP
The main file will contain the following code:
guestbook.php
=") == 1) error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); else error_reporting(E_ALL & ~E_NOTICE); require_once("classes/CMySQL.php"); // including service class to work with database // Get Visitor IP function getVisitorIP() ( $ip = "0.0.0.0"; if((isset($_SERVER["HTTP_X_FORWARDED_FOR"])) && (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))) ( $ip = $ _SERVER["HTTP_X_FORWARDED_FOR"]; ) elseif((isset($_SERVER["HTTP_CLIENT_IP"])) && (!empty($_SERVER["HTTP_CLIENT_IP"]))) ( $ip = explode(".",$_SERVER[ "HTTP_CLIENT_IP"]); $ip = $ip.".".$ip.".".$ip.".".$ip; ) elseif((!isset($_SERVER["HTTP_X_FORWARDED_FOR"])) | | (empty($_SERVER["HTTP_X_FORWARDED_FOR"]))) ( if ((!isset($_SERVER["HTTP_CLIENT_IP"])) && (empty($_SERVER["HTTP_CLIENT_IP"]))) ( $ip = $_SERVER ["REMOTE_ADDR"]; ) ) return $ip; ) // Get the latest entries in the guestbook function getLastRecords($iLimit = 3) ( $sRecords = ""; $aRecords = $GLOBALS["MySQL"]->getAll( "SELECT * FROM `s178_guestbook` ORDER BY `id` DESC L IMIT($iLimit)"); foreach ($aRecords as $i => $aInfo) ( $sWhen = date("F j, Y H:i", $aInfo["when"]); $sRecords .=<< ($aInfo["description"])