October 14th, 2009
The guest book on PHP/MySQL
Today I shall tell to you about how to write the guest book on PHP and MySQL. Anything complex{difficult} in it no, and opportunities given guest not the biggest: a paginal conclusion of recordings, check of the entered data, an opportunity to delete recording.
Today I shall tell to you about how to write the guest book on PHP and MySQL. Anything complex{difficult} in it no, and opportunities given guest not the biggest: a paginal conclusion of recordings, check of the entered data, an opportunity to delete recording.
We admit{allow}, that at you already is PHP, MySQL and the web – server. All of you have established and have adjusted.
Let’s start with creation of the table in which the data of our guest book will be stored{kept}. We shall ask the user a name and the comment. At desire the user can inform e-mail addresses and a homepage. For administration of the book we need one more field, unique for each recording, – the identifier. Well and date, certainly. In a result such table turns out:
CREATE TABLE gb (
id int (10) unsigned NOT NULL auto_increment,
datetime datetime DEFAULT ‘ 0000-00-00 00:00:00 ‘ NOT NULL,
name varchar (100) NOT NULL,
email varchar (100),
www varchar (100),
message text NOT NULL,
PRIMARY KEY (id)
);
The table at us is. Now it is possible to start programming.
For we shall create a file with adjustments of the guest book:
<? php
// The general{common} constants
define (‘PATH’, ‘/gb / ‘); // a way to the guest book
define (‘ RECSPERPAGE ‘, 10); // quantity{amount} of recordings on one page
define (‘ ADMIN_EMAIL ‘,’ artem@sapegin.ru ‘); // email the manager
define (‘ ERROR_LOG_FILE ‘,’ logs/error.log ‘); // a file of a broad gully of mistakes
// Parameters of a DB
define (‘ DBHOST ‘,’ localhost ‘); // the host name
define (‘ DBUSER ‘,’ root ‘); // a login name
define (‘ DBPASSWD ‘, “); // the password
define (‘ DBNAME ‘,’ test ‘); // a name of a database
?>
Now we shall think, what auxiliary functions will be necessary for us. On it will be necessary to cooperate with SUBD, will check up and to process the data entered by the user. As for functions of administration on it is required to distinguish the manager from simple users.
Let’s start with job with SUBD.
<? php
/ ** recource db_connect (string host, string user, string passwd, string dbname)
* Connection to SUBD and opening of a database
*/
function db_connect ($host, $user, $passwd, $dbname)
{
$link = mysql_pconnect ($host, $user, $passwd) or die (‘ Could not connect to database ‘);
mysql_select_db ($dbname) or die (‘ Could not select database ‘);
return $link;
}
/ ** Carries out search to a DB
*
* @param the text of search
* @return resource id
*/
function db_query ($query)
{
$result = mysql_query ($query)
or die (‘ Bad database query ‘);
return $result;
}
/ ** Carries out search to a DB (placeholder)
*
* @param the text of search
* @param*
* @return resource id
*/
function db_query_ex ($query)
{
$values = func_get_args ();
array_shift ($values);
$i = 0;
return db_query (preg_replace (‘ %? %e ‘,’ “‘” .addslashes ($values [$i ++]). “‘” ‘,
$query));
}
?>
Processing of lines (check and kill of the data entered by the user).
<? php
/ **
* Whether checks is the line e-mail address
*/
function strings_isemail ($string)
{
return preg_match (‘ % [-.w] + [-w] + (?:. [-w] +) + % ‘, $string);
}
/ **
* Addition of links on http and e-mail
*/
function strings_addlinks ($string)
{
return preg_replace (
‘ % ((?:http|ftp): // [-w] + (?:. [-w] +) +b [-w: and? = +! / ~ * $. ' %] *) (? <! [.?!)]) % i ‘,
‘ <a href = “\1 “> \1 <a> ‘,
$string
);
}
/ **
* Cleaning a line
*/
function strings_clear ($string)
{
$string = trim ($string);
$string = stripslashes ($string);
return htmlspecialchars ($string, ENT_QUOTES);
}
/ **
* Trimming a line
*/
function strings_stripstring ($text, $wrap, $length)
{
$text = preg_replace (‘ % (S {‘. $ wrap. ‘}) % ‘, ‘\1, $text);
return substr ($text, 0, $length);
}
?>
autentifikacii the manager I leave a spelling to you as the domestic task. There are many ways and their discussion – a subject of separate clause{article}. I shall result only function – zaglushku:
<? php
/ **
* Check: the manager or the usual user
*/
function auth_is_admin ()
{
return $ _GET [' admin '];
}
?>
Further goes enough the big module which contains almost all HTML-code of the guest book, – a pattern. In him there is nothing complex{difficult} and his{its} spelling is possible quite under force verstal`hhiku a site if at you those is present.
<? php
/ **
* Heading of page
*/
function template_header ($page)
{
?> <html>
<head>
<title> page <? = $page?> <fjGuestbook Demo </title>
<style>
body {
padding: 15px;
margin: 0;
color: *333;
background-color: *eee;
border-left: 30px solid *adba8e;
font: 500 .9em verdana, arial, helvetica;
}
a:link {color: *250;}
a:visited {color: *639;}
a:active, a:hover {
color: *c00;
text-decoration: underline;
}
h1 {font-size: 150 %;}
h2 {font-size: 110 %;}
.c {margin-bottom: 10px;}
.cn {
background-color: *d2d6bc;
padding: 2px 4px;
margin-bottom: 4px;
}
</style>
</head>
<body>
<h1> fjGuestbook Demo </h1> <? php
}
/ **
* The termination{ending} of page
*/
function template_footer ()
{
?>
<p> fjGuestbook 1.2. Copyright © 2002-2004
<a href = ” http: // sapegin.ru “> Artem Sapegin </a> </p>
</body> </html>
<? php
}
/ **
* The form of addition of new recording
*/
function template_form ($name, $email, $www, $message, $error)
{
// A conclusion of the message on a mistake
function error ($error)
{
if ($error) echo ‘ <br> <font color = * 880000> ‘. $ error.
‘ </font> ‘;
}
echo ‘ <h2> To add the new message </h2>
<p> <table cellspacing = “2″ cellpadding = “2″ border = “0″>
<form action = ‘.PATH. ‘? add=1 method=post> <tr>
<td> the Name <font color = * 880000> * </font>: </td>
<td> <input type=text name = “name” size=30
maxlength=100 value = ” ‘. $ name. ‘ “> ‘;
@error ($error [' name ']);
echo ‘ </td>
</tr> <tr>
<td> Email: </td>
<td> <input type=text name = “email” size=30
maxlength=100 value = ” ‘. $ email. ‘ “> ‘;
@error ($error [' email ']);
echo ‘ </td>
</tr> <tr>
<td> URL: </td>
<td> <input type=text name = “www” size=30
maxlength=100 value = ” ‘. $ www. ‘ “> ‘;
echo ‘ </td>
</tr> <tr>
<td> the Message <font color = * 880000> * </font>: </td>
<td> <textarea cols=40 rows=5
name = “message”> ‘. $ message. ‘ </textarea> ‘;
@error ($error [' message ']);
echo ‘ </td>
</tr> <tr>
<td> </td>
<td> <small> <font color = * 880000> * </font>
- Obligatory fields </small> </td>
</tr> <tr>
<td> </td>
<td> <input name = “sb” type=submit
value = ” To add the message “> </td>
</form> </tr>
</table> ‘;
}
/ **
* A seal of one recording the guest book
*/
function template_show_body ($id, $name, $email, $www, $message, $datetime)
{
$out = ‘ <div> <div> <b> ‘. $ name. ‘ </b> ‘;
// If is email or homepage – it is printed them
if ($email || $www)
{
$out. = ‘ (‘;
if ($email)
$out. = ‘ <a href=mailto: ‘. $ email. ‘> email </a> ‘;
if ($email ** $www)
$out. = ‘ | ‘;
if ($www)
$out. = ‘ <a href = ‘. $ www. ‘> www </a> ‘;
$out. = ‘) ‘;
}
$out. = ‘ writes ‘. $ datetime. ‘: </div> ‘. $ message. ‘ </div> ‘;
// If the guest book is looked through by the manager – print the button
// Removals{Distances} of recording
if (auth_is_admin ())
{
$out. = ‘ <div> [<a href = '.PATH. '? admin=1*del = '. $ id.
'> to remove </a>] </div> ‘;
}
return $out;
}
?>
And, we at last have reached the main thing. Up to the module of the guest book. I shall try to write more comments that to you it was understandable.
<? php
/ **
* Creation of the table if she{it} still no
*/
function gb_install ()
{
db_query (
‘ CREATE TABLE IF NOT EXISTS gb (
id int (10) unsigned NOT NULL auto_increment,
datetime datetime NOT NULL default ‘ 0000-00-00 00:00:00 ‘,
name varchar (100) NOT NULL default “,
email varchar (100) default NULL,
www varchar (100) default NULL,
message text NOT NULL,
PRIMARY KEY (id),
INDEX (datetime)
) TYPE=MyISAM; ‘
);
}
/ **
* Addition of recording in the guest book
*/
function gb_add ($name, $email, $www, $message, and $error)
{
// We check correctness of filling of fields
$error = “;
if (empty ($name))
$error [' name '] = ‘ This obligatory field ‘;
if (empty ($message))
$error [' message '] = ‘ This obligatory field ‘;
if (! empty ($email) **! strings_isemail ($email))
$error [' email '] = ‘ It not email ‘;
// If not was mistakes – it is added
if (! $error)
{
// We clean the data
$name = strings_clear ($name);
$message = strings_clear ($message);
$name = strings_stripstring ($name, 15, 100);
$email = strings_stripstring ($email, 100, 100);
$www = strings_stripstring ($www, 100, 100);
$message = strings_stripstring ($message, 100, 2000);
$message = nl2br ($message);
// If the user was too lazy to write http:// before the address – we shall make
// It for him{it}
if (! empty ($www) ** ‘ http:// ‘! = substr ($www, 0, 7))
$www = ‘ http: // ‘. $ www;
// Search about addition of recording in a database
db_query_ex (‘ INSERT INTO gb (name, email, www, message, datetime)
VALUES (????, NOW ()) ‘, $name, $email, $www, $message);
// We throw a browser on the first page
// It is necessary, that if the user will press button Refresh,
// Recording was not added once again
header (‘ Location: ‘.PATH. “? page=1 “);
}
}
// Removal{Distance} of recording from the guest book
function gb_delete ($id)
{
// Search about removal{distance} of recording from a database
// WHERE id = ‘. $ id specifies recording which should be removed
db_query_ex (‘ DELETE FROM gb WHERE id =? ‘, $id);
header (‘ Location: ‘.PATH. “? page=1 “); //???
}
// A conclusion of page with recordings
function gb_show ($page)
{
// Position of the first recording page
$begin = ($page – 1) * 10;
// Sample of recordings of a database
// SELECT * FROM gb – all fields from bd gb
// ORDER BY datetime DESC – sorting by date of, new from above
// LIMIT ‘. $ begin. ‘, ‘.RECSPERPAGE – restriction:
// RECSPERPAGE (see defines.php) recordings since $begin
$result = db_query (‘ SELECT * FROM gb ORDER BY datetime DESC LIMIT ‘.
$begin. ‘, ‘.RECSPERPAGE);
$out = “;
// A cycle on all chosen recordings
while ($row = mysql_fetch_array ($result))
$out. = template_show_body ($row [' id '], $row [' name '], $row [' email '],
$row [' www '], $row [' message '], $row [' datetime ']);
// We destroy result
mysql_free_result ($result);
echo $out;
}
// A conclusion of the list of pages
function gb_showpages ($current)
{
// We learn{We find out} number of recordings in the guest book
$result = db_query (‘ SELECT * FROM gb ‘);
$rows = mysql_num_rows ($result);
if ($rows)
{
$pages = ceil ($rows / RECSPERPAGE);
// We print links to pages (number{room} of the current page is not the link)
echo ‘ <div> ‘;
for ($i = 1; $i <= $pages; $i ++)
{
if ($i! = $current)
echo ‘ | <a href = ‘.PATH. ‘? page = ‘. $ i. ‘>’. $ i. ‘ </a> ‘;
else
echo ‘ | ‘. $ i;
}
echo ‘ | ‘;
// If it not polslednjaja page we print the link “Further”
if ($current <$pages)
echo ‘> a href = ‘.PATH. ‘? page = ‘. ($ current + 1).
‘> is Farther>> </a> ‘;
echo ‘ </div> ‘;
}
}
?>
And the last – it is united all together.
<? php
/ **
* fjGuestbook 1.2
*
* A nucleus of the guest book
*
* Copyright 2002-2004 Artem Sapegin
* http://sapegin.ru
*/
// We connect modules
require_once ‘ my/defines.php ‘;
require_once ‘ my/template.php ‘;
require_once ‘ engine/lib/strings.php ‘;
require_once ‘ engine/lib/auth.php ‘;
require_once ‘ engine/lib/bd.php ‘;
require_once ‘ engine/gb.php ‘;
// We are connected to a DB
db_connect (DBHOST, DBUSER, DBPASSWD, DBNAME);
// We create the table if she{it} no
gb_install ();
// We obtain the given forms if the form has been sent
if (! empty ($ _POST [' sb ']))
{
$name = $ _POST [' name '];
$email = $ _POST [' email '];
$www = $ _POST [' www '];
$message = $ _POST [' message '];
$formerr = “;
}
else
{
$name = $email = $www = $message = $formerr = “;
}
// If number{room} of page is not specified in GET-search, we deduce{remove} the first
if (is_numeric ($ _GET [' page ']))
$page = $ _GET [' page '];
else
$page = 1;
// If it is necessary to add recording, we add
if ($ _GET [' add '])
gb_add ($name, $email, $www, $message, $formerr);
// If it is necessary to remove recording, we delete
if (isset ($ _GET [' del ']) ** auth_is_admin ())
gb_delete (intval ($ _GET [' del ']));
// We print the guest book
template_header ($page);
gb_showpages ($page);
gb_show ($page);
gb_showpages ($page);
template_form ($name, $email, $www, $message, $formerr);
template_footer ();
?>