Tuesday, April 13, 2010

PHP

I finished the php Prac from yesterday (the guestbook) and have it up and running here: (although I deliberately left out the images- so apologies for that).




I thought I would run you through some of the obstacles I came across in case you have the same issues:


Setting up a database:

Most of it was pretty straight forward- I followed the instructions in the script- made sure id was set to 'not null' and 'auto increment'. I just got a little stuck understanding about the primary key making the primary key the 'id' field- I needed to look for the button that made it the primary key.

"SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Each table should have a primary key, and each table can have only one primary key."

http://www.w3schools.com/sql/sql_primarykey.asp


Modifying the file to connect to the database:

My 000webhost members area had all the info to plug straight into the script directly under the instructions in quotation marks. The only one that got me stuck was the server- which was a different server from the one listed on the front page on the members area, I just needed to search the MySQL area for the database server.

Uploading:
No problems! Just used Filezilla and after rectifying the server issue, it all worked fine.

Adding a 'country' field:
Firstly, country needed to be added to the database table.
My strategy for this was simple- I scoured the document and every time I found 'name' 'email' and 'message' I added 'country' in the same syntax the others were in. First time round, I managed to get the JavaScript happening- new field and being able to type in the field, but wouldn't have 'country' emailed or appear at the top of the guest book. I went through it again, found that I had missed a couple of sections and did it again. Managed to get it to email, but not appear at the top of the page or add to the database. Finally found the part of the script that added it to the database and it all worked fine. I've hi-lighted all the changes I made to the script below.


__________________________________________________________________





Guestbook







::Guestbook - A::


dbc = mysql_connect($server, $user, $password) or die ("Connection failed!");
mysql_select_db($database) or die ("Database failed!");
}
/* DISPLAY RECORDS */
function display_records($offset, $entries_per_page)
{
$this->result = mysql_query("SELECT id, name, email, country, message, date FROM $this->table ORDER BY id DESC LIMIT $offset, $entries_per_page") or die ("Query failed!");
while ($row = mysql_fetch_array($this->result)) {
// SOME NICE FORMATTING HERE;
$display_name = nl2br(htmlspecialchars($row["name"]));
$display_email = nl2br(htmlspecialchars($row["email"]));
$display_country = nl2br(htmlspecialchars($row["country"]));
$display_message = nl2br(htmlspecialchars($row["message"]));
// THIS ALLOWS USING SMILIES AND IS NOT DANGEROUS;
$display_message = str_replace ("<img src=smiles/", "", $display_message);
// DISPLAY WHAT WE HAVE AT LAST;
echo "
Name: [" . $display_name . " ], Country: [" . $display_country . "], " . $row["date"] . "
" . "Email: " . $display_email . "

" . $display_message;

}
/******************************************************************************/
/* This code here handles pages stuff, number and next/previous links, etc. */
/* If you don't need some of the features, just delete corresponding parts. */
/******************************************************************************/
$this->count_result = mysql_query("SELECT count(id) AS number FROM $this->table") or die ("Query failed!");
while ($count = mysql_fetch_array($this->count_result)) {
$total_entries = $count["number"];
}
// HOW MANY PAGES OF RECORDS WE HAVE;
// THIS BLOCK IS ESSENTIAL FOR FURTHER PARTS;
$pages = $total_entries / $entries_per_page;
if ($pages < pages =" 1;"> 1) {
$pages = (int) $pages + 1;
}
else {
$pages = $pages;
}
if (($offset > $total_entries) or (!is_numeric($offset)))
$offset = 0;
// CURRENT PAGE NUMBER;
$pagenow = ($offset/$entries_per_page + 1);
echo "

* * *
Page " . $pagenow . " of " . $pages;
// NEXT/PREVIOUS PAGE LINKS DISPLAY
$next = $offset + $entries_per_page;
$previous = $offset - $entries_per_page;
if ($pages <> 1) {
echo " || ";
if ($previous < href="http://www.blogger.com/gb.php?offset=">";
echo ">>>";
}
elseif ($next >= $total_entries) {
echo "";
echo "<<<
";
}
else {
echo "";
echo "<<<
";
echo " | ";
echo "";
echo ">>>
";
}
echo "

";
}
// DISPLAY LINKS TO ALL PAGES SEPARATELY;
echo "
Pages: ";
$i = 0;
while ($i < $pages) { $ri = $i + 1; $showpage = $i * $entries_per_page; if ($ri == $pagenow) echo $ri . " "; else echo "" . $ri . " ";
$i++;
}
echo "
";
}
/******************************************************************************/
/* End of pages code, this section is the longest, but you get pages features */
/******************************************************************************/
/* ADD RECORDS TO DATABASE */
function add_record($name, $email, $country, $message, $smilies="on", $webmaster, $message_length, $language_filter, $bad_words)
{
if ($email == "") {
$email = "no_email";
}
// IF LANGUAGE FILTER IS ENABLED AND WEBMASTER EMAIL ADDRESS DEFINED DO THIS;
if (($language_filter == 1) and (strlen($webmaster) <> 0)) {
for ($i=0;$i<> 0) {
$message = substr($message, 0, $message_length);
}

// IF USER USES SMILIES DO THIS;
if ((isset($smilies)) and ($smilies == "on")) {
$format_smilies = array (
":-)", "\'Smile\'",
"8-)", "\'Glasses\'",
":(", "\'Angry\'",
":-D", "\'Big",
"%-)", "\'I",
">8-|", "\'Evil\'",
":-o", "\'Kiss",
"?", "\'Question\'",
":-(", "\'Sad\'",
"[$-)", "\'Sleepy\'",
":-P", "\'Tongue\'",
";-)", "\'Wink\'"
);

for ($i=0;$ithis->result = mysql_query("INSERT INTO $this->table (name, email, country, message, date) VALUES ('$name', '$email', '$country', '$message', NOW())");
// When guestbook is signed a message is emailed
// to webmaster if this feature is enabled;
if (strlen($webmaster) <> 0) {
$sendmessage = "Name: " . $name . "\nCountry: " . $country . "\nEmail: " . $email . "\nMessage: " . $message;
@mail($webmaster, "Guestbook signed", $sendmessage);
}
if (!$this->result)
echo "Error!";
}
/* DISCONNECT FROM DATABASE */
function disconnect_db()
{
mysql_close($this->dbc);
}
}
/******************************************************************************/
/* END OF GUESTBOOK CLASS */
/******************************************************************************/


/******************************************************************************/
/* INSTALLATION: */
/* 1) create a table in the MYSQL database with a query: */
/* CREATE TABLE guestbook ( */
/* id int(5) NOT NULL auto_increment, */
/* name varchar(50), */
/* email varchar(50), */
/* message text, */
/* date datetime, */
/* PRIMARY KEY (id) */
/* ) */
/* 2) define some variables below as they suit your environment; */
/* 3) possibly change any formatting in the display_records() function; */
/* 4) copy gb.php to your server and enjoy; */
/******************************************************************************/
// Let's define some variables;
$webmaster = 'ts_richardson@yahoo.com.au'; // EMAIL ADDRESS TO SEND WARNINGS TO
// WHEN GUESTBOOK IS SIGNED; LEAVE
// EMPTY IF YOU WANT THIS FEATURE
// DISABLED;
$server = 'mysql12.000webhost.com'; // DATABASE SERVER;
$database = 'a4186211_wp'; // DATABASE NAME;
$user = 'a4186211_tsr'; // USER TO CONNECT TO DATABASE;
$password = 'mypassword'; // USER PASSWORD;
$entries_per_page = 5; // HOW MANY RECORDS PER PAGE;
$message_length = 1024; // MESSAGE LENGTH ALLOWED, LEAVE 0
// IF YOU WANT ANY SIZE MESSAGES,
// THIS CUTS MESSAGE TO DEFINED SIZE;
$language_filter = 1; // 1 - enable language filter;
// 0 - disable language filter;
$bad_words = array ( // Bad words vocabulary (add your own);
'bottom', 'trousers'
);
// Let's spawn an instance of guestbook class;
$myGB = new Guestbook;
$myGB->connect_db($server, $database, $user, $password);

// aw- put the POST variables into the variables used in the script
$message = $_POST['message'];
$email = $_POST['email'];
$country = $_POST['country'];
$name = $_POST['name'];
$smilies = $_POST['smilies'];

// If user submitted form, add a record;
if (isset($message)) {
if (!isset($smilies))
$myGB->add_record($name, $email, $country, $message, "no", $webmaster, $message_length, $language_filter, $bad_words);
else
$myGB->add_record($name, $email, $country, $message, $smilies, $webmaster, $message_length, $language_filter, $bad_words);
}
// If opened without $offset variable defined, it is zero;
if ((!isset($offset)) or ($offset < offset =" 0;">display_records($offset, $entries_per_page);
$myGB->disconnect_db();
?>
and the form:
* Name:


Email:


Country:


* Message:








No comments:

Post a Comment