TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 01-23-2008, 05:08 PM   #1 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default Creating a guest book

Hello there,

Some one mentioned that I created a guest book to improve my PHP skills, I thought this was a really good idea and took on the challenge! Unfortunately I don't think I have the skills right now to be able to create one, but here's what I've done so far:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Guest Book</title>
  <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
  
  <script language="JavaScript" type="text/JavaScript">

		<!--This will hide our code from old browsers
		   
		  // JavaScript code goes here

      function validateForm()
      {
         with (document.guest_book) {
            
            errorfields=""
            
            //Check Name
            if (username.value == "") {
               errorfields=errorfields + "Name \n"
            }
            
            //Check email for @ and '.'
            if ((Email.value.length <6) || (Email.value.indexOf('@') <0) || (Email.value.indexOf('.') <0))  {
                errorfields=errorfields + "Please enter a valid Email address \n"
            }
            
            //Check comment
            if (comment.value == "") {
               errorfields=errorfields + "Please write your comment \n"
            }
            
            
            if (errorfields!="") {
               alert("The following fields much be entered: \n\n"  + errorfields)
               return false;
            }
        }
        return true;
      }

	// End hiding script from non-JavaScript browsers-->

	   </script>
	   
	   <noscript>Your browser has disabled Javascript</noscript>
	   
</head>
<body>

<!--Sign guest book form-->

<div align="center">
  <form name="guest_book" id="guestbooktable" method="post" action="results.php" onSubmit="return validateForm()">
    <table>
      <tr>
        <td>  *Name:   </td>
        <td>  <input type=text name=username size=30 /> </td>
      </tr>
      
      <tr>
        <td></td>
        <td></td>
      </tr>
      
      <tr>
        <td>  Email:   </td>
        <td>  <input type=text name=Email size=30 /> </td>
      </tr>
      
      <tr>
        <td></td>
        <td></td>
      </tr>
      
      <tr>
        <td>  Website:   </td>
        <td>  <input type=text name=website size=30 /> </td>
      </tr>
      
      <tr>
        <td></td>
        <td></td>
      </tr>
      
      <tr>
        <td>  Comment:   </td>
        <td>  <textarea name=comment rows=5 cols=40></textarea> </td>
      </tr>
      
       <tr>
        <td>  </td>
        <td>  <input type=submit name=submit value=Submit /> <input type=reset name=reset value=Reset /> </td>
      </tr>
    </table> 
  </form>
</div>
</body>
</html>
I've created a form and validated all the fields. I've then created a PHP page:

Code:
<?
$username=$_POST['username'];
$email=$_POST['Email'];
$websiteurl=$_POST['website'];
$comment=$_POST['comment'];
?>

<head>
	<title>Cookies</title>
		<script language="JavaScript" type="text/JavaScript">
			<!--This will hide our code from old browsers
		
		//Date
       now = new Date
       
	   dayNames = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
              
	   monthNames = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",              "December")

		dateNames = new Array ( "", "1st",  "2nd",  "3rd",  "4th",  "5th",  "6th",  "7th",  "8th", "9th", "10th", "11th", "12th", "13th", "14th",             "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st")
</script>
	   
	   <noscript>Your browser has disabled Javascript</noscript>
</head>
	
<div align="center">
	<table border="1">
	  <tr>
		<td width="74" rowspan="2">&nbsp;</td>
		<td width="435">
			<? echo $username; ?>  | <? echo $email; ?>  | 
			<script  language="javascript"  type="text/javascript">
              //Day
              document.writeln(dayNames[now.getDay()])
              //Date
              document.writeln(dateNames[now.getDate()])
              //Month
              document.writeln(monthNames[now.getMonth()])
              //Year
              document.write(now.getFullYear())

              </script>
		</td>
	  </tr>
	  <tr>
		<td><? echo $comment; ?></td>
	  </tr>
	</table>
</div>
What it does at the moment is shows all of the data entered in the form by using _POST. I'm not sure yet how I get that data to stay there so I can exit the page and leave another comment. Is this difficult?

Thanks,
Steven
StevenF is offline  
Reply With Quote
Old 01-23-2008, 05:43 PM   #2 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default

Store your information in a database. I'd somewhat explain this, but I'm off to the pub soon and don't have time

Look up tutorials on how to store values into a database.
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 01-23-2008, 05:43 PM   #3 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

If I where writing a guestbook script, it would probably flow something like the following:

Code:
1. Display guestbook to user
2. User clicks "Add Comment" link
3. Display the new comment form
4. User fills in form and submits
5. Check / Validate $_POST input
6. Connect to the database
7. Insert the new entry into the database
8. Close database connection
9. Display a "Thank you" message if insert was sucessful
10. Redirect user back to the guestbook
Hopefully this will get you going in the right direction

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
StevenF (01-23-2008)
Old 01-23-2008, 06:06 PM   #4 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

Quote:
Originally Posted by Alan @ CIT View Post
If I where writing a guestbook script, it would probably flow something like the following:

Code:
1. Display guestbook to user
2. User clicks "Add Comment" link
3. Display the new comment form
4. User fills in form and submits
5. Check / Validate $_POST input
6. Connect to the database
7. Insert the new entry into the database
8. Close database connection
9. Display a "Thank you" message if insert was sucessful
10. Redirect user back to the guestbook
Hopefully this will get you going in the right direction

Alan
Thanks for that, I totally forgot about the Database Do I create a database called "guesbook" for example, then add the fields which will be in the form? E.g. Name, email, website, comment?
StevenF is offline  
Reply With Quote
Old 01-23-2008, 06:58 PM   #5 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

I've wrote this PHP:

Code:
<? 
$username="";
$password="";
$database="guestbook";
$yourname=$_POST['yourname'];
$email=$_POST['Email'];
$websiteurl=$_POST['website'];
$comment=$_POST['comment'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("Unable to select database");
$query="INSERT INTO entries (name, email, website, comment) VALUES ($username, $email, $website, $comment)";

mysql_close();
?>
That should open the connection, gather all of the data from the form and creates a query to insert that data into the forum? I'm not sure how I then go about entering that data into the database when the submit button is pressed.
StevenF is offline  
Reply With Quote
Old 01-23-2008, 07:40 PM   #6 (permalink)
The Addict
 
Join Date: Nov 2007
Posts: 264
Thanks: 2
TlcAndres is on a distinguished road
Default

You'll want to escape that data with mysql_real_escape_string
TlcAndres is offline  
Reply With Quote
Old 01-23-2008, 07:40 PM   #7 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

Quote:
Originally Posted by StevenF View Post
I've wrote this PHP:

Code:
<? 
$username="";
$password="";
$database="guestbook";
$yourname=$_POST['yourname'];
$email=$_POST['Email'];
$websiteurl=$_POST['website'];
$comment=$_POST['comment'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("Unable to select database");
$query="INSERT INTO entries (name, email, website, comment) VALUES ($username, $email, $website, $comment)";

mysql_close();
?>
That should open the connection, gather all of the data from the form and creates a query to insert that data into the forum? I'm not sure how I then go about entering that data into the database when the submit button is pressed.
Is there suppose to be a username and password on your database?
If you have a username and password, then you need to enter that in, otherwise username and password variables can be null
__________________
VillageIdiot can have my babbies ;d
Orc is offline  
Reply With Quote
Old 01-23-2008, 08:05 PM   #8 (permalink)
The Frequenter
 
ReSpawN's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 460
Thanks: 49
ReSpawN is on a distinguished road
Default

Don't take up too much work at one time. ("Don't bite off more than you can chew")
I've learned from experience that if you take bite off more than you can chew, you'll end up not finishing the work or dropping it all together. Make readable, tidy scripts. Use spaces, enters, tabs and more important, invent your own style. Things like securing your scripts is something that you'll learn later on, but it's a good way to start.

One other thing hat you can do, is simply follow a LOT of tutorials or download pre-made guestbooks and try to rescript yours from scratch, using what you have learned from the other scripts.

I made it on the go, I haven't tested it, I haven't payed that much attention (chatting with girls, you know the drill) but I wish you luck. If you find a bug, try to fix it yourself, otherwise, just post it! Apologies in that case.
PHP Code:
<?php

    
// Databse information
        /* Usally this is set in the config, later on included (include('config.php');) */
    
$host 'localhost';
    
$username ''// Using a WAMP/XAMP server
    
$password '';
    
$database 'guestbook';

    
// MySQL Connections
        /* In almost ALL scripts, mysql_connect and select_db (if not MySQLi) are
           called uppon in the header or otherwise in the top of the document, later
           killing it with mysql_close(); (if you're using a persistant connection).
           Again, this is either done in your config.php or in an advanced class or 
           document, designed to handle those things. */
    
mysql_connect($localhost$username$password) or die ('<strong>MySQL Error:</strong> '.mysql_error());
    
mysql_select_db($database) or die ('<strong>MySQL Error:</strong> '.mysql_error());

    
// Recent information
    
$yourname addslashes($_POST['yourname']);
        
/* Why use this if you already designated a variable called $username ? */
    
$email urlencode(addslashes($_POST['email']));
        
/* Do NOT use upper capitals in your posts, you might confuse them and you
           end up exploring your own code searching for some minor bugs */
    
$website urlencode(addslashes($_POST['website']));
    
$comment htmlentities(addslashes(strip_tags($_POST['comment'])));
        
/* Still haven't fully explored the precise method of filtering the message */
    
    
$query 'INSERT INTO entries SET    name = "'.mysql_real_escape_string($username).'",
                                        email = "'
.mysql_real_escape_string($email).'",
                                        website = "'
.mysql_real_escape_string($website).'",
                                        comment = "'
.mysql_real_escape_string($comment).'"';
    
mysql_query($query);

    
mysql_close();
    
?>
</b>
__________________
"Life is a bitch, take that bitch on a ride"
Send a message via MSN to ReSpawN
ReSpawN is offline  
Reply With Quote
The Following User Says Thank You to ReSpawN For This Useful Post:
StevenF (01-23-2008)
Old 01-23-2008, 08:46 PM   #9 (permalink)
The Wanderer
 
Join Date: Jan 2008
Posts: 12
Thanks: 0
karq is on a distinguished road
Default

U can save those comments into a txt fail, its easier then inserting data to mysql database.
Just use:
fopen;
fwrite;
fclose;
and then include that txt fail on that page where u want those comments.
karq is offline  
Reply With Quote
Old 01-23-2008, 08:50 PM   #10 (permalink)
The Contributor
 
Join Date: Dec 2007
Location: Florida
Posts: 73
Thanks: 12
danielneri is on a distinguished road
Default

karg, you could use flat file storage, but then you'd run into a bunch of security problems and it's generally a pain in the ass

Using a database, although maybe a little more difficult(debatable?), is good for the long run and is a must-know for any PHP developer.
__________________
Send a message via AIM to danielneri
danielneri is offline  
Reply With Quote
Old 01-23-2008, 09:13 PM   #11 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

Quote:
Originally Posted by Orc View Post
Is there suppose to be a username and password on your database?
If you have a username and password, then you need to enter that in, otherwise username and password variables can be null
No the database has no username or password, that's why I've left them blank.

ReSpawN:
Thank you ever so much for doing that. I can see I had the logic sorted out (I think), but had some syntax wrong. When setting variables, you've used: addslashes, urlencode and [i]htmlentities[/I. I haven't actually used them before and I'll need to look up what each of them do.

I'll have a play around with it and see what I can come up with!
StevenF is offline  
Reply With Quote
Old 01-24-2008, 12:26 AM   #12 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

It works!

Code:
<?php

  // Database information
    /* Setting username and password */
    $username="";
    $password="";
    $database="guestbook";
    
  // MySQL Connections
    mysql_connect($localhost, $username, $password) or die ('<strong>MySQL Error:</strong> '.mysql_error());
    mysql_select_db($database) or die ('<strong>MySQL Error:</strong> '.mysql_error());
    
   // Setting variables
    $yourname = addslashes ($_POST['yourname']);
    $email = urlencode(addslashes($_POST['email']));
    $websiteurl = urlencode(addslashes($_POST['website']));
    $comment = htmlentities(addslashes(strip_tags($_POST['comment'])));
   
   // Creating the query to store the data entered in the database
    $query = 'INSERT INTO entries SET   name = "'.mysql_real_escape_string($yourname).'",
                                        email = "'.mysql_real_escape_string($email).'",
                                        website = "'.mysql_real_escape_string($website).'",
                                        comment = "'.mysql_real_escape_string($comment).'"';
    mysql_query($query);
    
      // Display all of the saved records in the database
      $guessbookentries = 'SELECT * FROM entries';
      
      $result = mysql_query($guessbookentries); 
	  
	  // Return all rows from the above query 
	  $num=mysql_numrows($result);
    
      // Close connection
  	  mysql_close();
   
?>

<html>
<head>
	<title>Cookies</title>
	<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
		<script language="JavaScript" type="text/JavaScript">
			<!--This will hide our code from old browsers
		
		//Date
      var mydate = new  Date()
      var year = mydate.getYear()
      if (year < 1000)
      year+=1900
      var day = mydate.getDay()
      var month = mydate.getMonth()+1
      if (month<10)
      month="0"+month
      var daym = mydate.getDate()
      if (daym<10)
      daym = "0"+daym
      
      // Time
      

</script>
	   
	   <noscript>Your browser has disabled Javascript</noscript>
</head>
<body>

	<h1 align="center"><a href="index.php">Sign Guest Book</a></h1>
<?

	// Loop
	$i=0;
	while ($i < $num) {
	
	$guestname = mysql_result($result, $i, "name");
	$guestemail = mysql_result($result, $i, "email");
	$guestwebsite = mysql_result($result, $i, "website");
	$guestcomment = mysql_result($result, $i, "comment");

?>
	
<div align="center">
  <table width="500" border="1" bordercolor="#0066FF" id="guestbooktable">
    <tr>
      <td width="58" rowspan="2">&nbsp;</td>
      <td width="426">
	  	<script  language="javascript"  type="text/javascript">
              // Date
               document.write("<small>"+month+"/"+daym+"/"+year+"</small>") 
       </script>	 </td>
    </tr>
    <tr>
      <td height="61"> <? echo $guestname; ?> <br /> <br /><? echo $guestcomment; ?></td>
    </tr>
  </table>
</div>

<?

$i++;
}

?>
</table>
</div>
</body>
</html>
The only problem I have is: When I enter a new entry into the guest book, it doesn't go to the top of the list, it goes to the second top for some reason.

I was also wondering if someone could explain this:

Code:
<?

	// Loop
	$i=0;
	while ($i < $num) {
	
	$guestname = mysql_result($result, $i, "name");
	$guestemail = mysql_result($result, $i, "email");
	$guestwebsite = mysql_result($result, $i, "website");
	$guestcomment = mysql_result($result, $i, "comment");

?>
That's not making 100% sense to me at the moment, I pulled it from something I was doing a few days ago and it worked.

i=0 so while (0 is less than $num (the number of rows in the query) then display the next set of variables. I don't understand how "i" can ever become less than "$num".
StevenF is offline  
Reply With Quote
Old 01-24-2008, 12:27 AM   #13 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

mysql_result is deprecated, no need for it.
__________________
VillageIdiot can have my babbies ;d
Orc is offline  
Reply With Quote
Old 01-24-2008, 12:30 AM   #14 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

When I delete mysql_result from
Code:
<?

	// Loop
	$i=0;
	while ($i < $num) {
	
	$guestname = mysql_result($result, $i, "name");
	$guestemail = mysql_result($result, $i, "email");
	$guestwebsite = mysql_result($result, $i, "website");
	$guestcomment = mysql_result($result, $i, "comment");

?>
I get an error.
StevenF is offline  
Reply With Quote
Old 01-24-2008, 12:31 AM   #15 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

We need to use the function tags more..
array_splice
__________________
VillageIdiot can have my babbies ;d
Orc is offline  
Reply With Quote
Old 01-24-2008, 12:31 AM   #16 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

Quote:
Originally Posted by StevenF View Post
When I delete mysql_result from
Code:
<?

	// Loop
	$i=0;
	while ($i < $num) {
	
	$guestname = mysql_result($result, $i, "name");
	$guestemail = mysql_result($result, $i, "email");
	$guestwebsite = mysql_result($result, $i, "website");
	$guestcomment = mysql_result($result, $i, "comment");

?>
I get an error.
Remove the whole loop..
__________________
VillageIdiot can have my babbies ;d
Orc is offline  
Reply With Quote
Old 01-24-2008, 12:33 AM   #17 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

Quote:
Originally Posted by Orc View Post
We need to use the function tags more..
array_splice
To much information for one night, getting tired lol.

Quote:
Originally Posted by Orc View Post
Remove the whole loop..
I don't understand how the entries will display if I remove that...
StevenF is offline  
Reply With Quote
Old 01-24-2008, 12:35 AM   #18 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

Quote:
Originally Posted by StevenF View Post
To much information for one night, getting tired lol.



I don't understand how the entries will display if I remove that...
PHP Code:

 
while ( $row mysql_fetch_array($query) )
 {
   
// You put the row now, such as if you wanted to grab someones username from a database it'd be:
   
echo  $row['username'];
 
// and it would display

  

__________________
VillageIdiot can have my babbies ;d
Orc is offline  
Reply With Quote
The Following User Says Thank You to Orc For This Useful Post:
StevenF (01-24-2008)
Old 01-24-2008, 11:48 AM   #19 (permalink)
The Contributor
 
Join Date: Dec 2007
Location: Florida
Posts: 73
Thanks: 12
danielneri is on a distinguished road
Default

Whoa wait: side note

mysql_result is deprecated?! what replaced it? and when?

wow where have I been...
__________________
Send a message via AIM to danielneri
danielneri is offline  
Reply With Quote
Old 01-24-2008, 11:56 AM   #20 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

mysql_result() isn't officially depreciated as far as I know.

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 07:37 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design