• home
  • forum
  • my
  • kt
  • download
  • Create a Basic Shoutbox with PHP and SQL

    Author: 2009-03-08 09:57:32 From:

    Introduction

    This tutorial will guide you through the process of creating a basic "shoutbox" with PHP, using a MySQL database to store the shouts - and then make it look nice with some CSS. The tutorial is aimed at designers who are confident with HTML & CSS, but want to try their hand at developing with PHP.

    Following the tutorial, you should hopefully have a good understanding of the basics of using PHP to communicate with a database to send, request and receive information. We will also be including the use of Gravatars in our Shoutbox, adding that little extra oomph!

    For those who haven't, I recommend you read our PHP From Scratch series in order to understand exactly what PHP is, and get a look at some of the basic syntax and how we use variables.

    The sources files are also commented for those who would prefer to learn that way.

    Step 1 - Getting Started

    Database

    Before starting, you should already have a database setup on your web server. Make sure you have the following details at hand:

    • Hostname (eg. localhost)
    • Database name
    • Username for database
    • Password

    In the database, you will need to create a table named shouts with five fields:

    • id
    • name
    • email
    • post
    • ipaddress

    To create this, run the following SQL code. You will normally run this from the SQL tab in phpMyAdmin.

    view plaincopy to clipboardprint?
    1. CREATE TABLE `shouts` (   
    2.   `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,   
    3.   `nameVARCHAR(45) NOT NULL,   
    4.   `email` VARCHAR(60) NOT NULL,   
    5.   `post` TEXT NOT NULL,   
    6.   `ipaddress` VARCHAR(45) NOT NULL,   
    7.   PRIMARY KEY (`id`)   
    8. );  

    You should receive a "Your SQL query has been executed successfully" message

    The Files

    We will need three files created for this project:

    • index.php
    • style.css
    • db.php

    You will also need a folder with our required images. Grab this from the source files.

    Database Connection Details

    The db.php file will be used to store our database details. Open it and insert the following code:

    view plaincopy to clipboardprint?
    1. <?php   
    2. $host = 'localhost'//usually localhost   
    3. $username = 'root'//your username assigned to your database   
    4. $password = 'password'//your password assigned to your user & database   
    5. $database = 'shoutbox'//your database name   
    6. ?>  

    Step 2 - Interaction

    Start your index.php file with the following code, it just begins our document and places a few sections to style later.

    view plaincopy to clipboardprint?
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    2. <html xmlns="http://www.w3.org/1999/xhtml">  
    3. <head>  
    4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
    5. <title>Shoutbox for NETTUTS by Dan Harper</TITLE>  
    6. <link rel="stylesheet" href="style.css" type="text/css" />  
    7. </head>  
    8. <body>  
    9. <div id="container">  
    10.   
    11.   <h1>Shoutbox<H1></H1>  
    12.   <h5><a href="http://www.danharper.me" title="Dan Harper">Dan Harper </a> : <a href="http://www.nettuts.com" title="NETTUTS - Spoonfed Coding Skills">NETTUTS</a></h5>  
    13.   
    14.   <div id="boxtop" />  
    15.   <div id="content">  

    Establishing a Connection

    Before we can do anything with a database, we need to connect to it. Insert the following after the previous code. It is explained below.

    view plaincopy to clipboardprint?
    1. <?php   
    2. $self = $_SERVER['PHP_SELF']; //the $self variable equals this file   
    3. $ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP   
    4. include ('db.php'); // for db details   
    5.   
    6. $connect = mysql_connect($host,$username,$passwordor die('<P class=error>Unable to connect to the database server at this time.</P>');   
    7.   
    8. mysql_select_db($database,$connector die('<P class=error>Unable to connect to the database at this time.</P>');  

    The first two lines use a built-in PHP function to get the name of this file, and the other line to get the visitors IP address. We will use the two variables later in the tutorial.

    We then include our db.php file so we can retrieve the database details you filled in. Alternatively, you could paste everything from db.php here, but it's good practice to separate the details.

    $connect stores a function to use our database details in order to establish a connection with the database server. If it can't connect, it will display an error message and stop the rest of the page loading with die().

    Finally, we connect to our database.

    Has anything been submitted?

    The next thing we will do is check whether someone has submitted a shout using the form (which we will include shortly). We check the documents POST to see if something has been submitted from a form.

    view plaincopy to clipboardprint?
    1. if(isset($_POST['send'])) {   
    2.     if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {   
    3.         echo('<P class=error>You did not fill in a required field.</P>');   
    4.     } else {  

    We start with our if() which checks our POST to see if an item named 'send' has been submitted. If it has we use the empty() function to make sure the 'name', 'email' and 'post' fields were filled in. If they weren't, we display an error.

    Otherwise, we continue:

    view plaincopy to clipboardprint?
    1. $name = htmlspecialchars(mysql_real_escape_string($_POST['name']));    
    2. $email = htmlspecialchars(mysql_real_escape_string($_POST['email']));    
    3. $post = htmlspecialchars(mysql_real_escape_string($_POST['post']));   
    4.   
    5. $sql = "INSERT INTO shouts SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';";   
    6.   
    7.     if (@mysql_query($sql)) {   
    8.         echo('<P class=success>Thanks for shouting!</P>');   
    9.     } else {   
    10.         echo('<P class=error>There was an unexpected error when submitting your shout.</P>');   
    11.     }   
    12. }   
    13. }  

    On the first three lines, we run each of our fields (name, email and post) through the htmlspecialchars() and mysql_real_escape_string() functions and place them into their own variables.

    htmlspecialchars() is a function designed to prevent users from submitting HTML code. If we didn't do this, someone could put any HTML into our database which would then be executed to other users. This is especially bad if someone submitted javascript code that would transfer visitors to a malicious website!

    mysql_real_escape_string() is a similar function. Except this one stops the user from submitting any sort of SQL code to the server. If we didn't do this, someone could execute code to steal, edit or erase our database!

    Using our new details, we create a SQL query to insert the submitted shout into the database. In the if() tags, we execute the SQL Query. If the query was successfully executed, and the shout added to the database, we display a "Thanks for shouting!" message; otherwise we display an error.

    Retrieving the Shouts

    We will now retrieve the 8 latest shouts from our database to display them to the user.

    view plaincopy to clipboardprint?
    1. $query = "SELECT * FROM `shouts` ORDER BY `id` DESC LIMIT 8;";   
    2.        
    3. $result = @mysql_query("$query"or die('<P class=error>There was an unexpected error grabbing shouts from the database.</P>');   
    4.   
    5. ?><UL><?   
    6. </pre>   
    7. <P>On the first line, we create a new SQL query to "Retrieve all fields from the 'shouts' table, order them descending by the 'ID'; but only give us the latest 8".</P>   
    8. <P>On the second line we execute the query and store it in $result. We now:</P>   
    9. <PRE class=php name="code">while ($row = mysql_fetch_array($result)) {   
    10.   
    11.     $ename = stripslashes($row['name']);   
    12.     $eemail = stripslashes($row['email']);   
    13.     $epost = stripslashes($row['post']);   
    14.        
    15.     $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";    
    16.        
    17.     echo('<LI><DIV class=meta><IMG alt=Gravatar src="'.$grav_url.'">  
    18.     <P>'.$ename.'</P></DIV><DIV class=shout><P>'.$epost.'</P></DIV>');   
    19.   
    20. }   
    21. ?></LI></PRE></UL>  
    '); } ?>

    The%20first%20line%20says%20"While%20there%20are%20still%20rows%20(results)%20inside%20$result,%20display%20them%20as%20follows:".

    stripslashes()%20removes%20any%20slashes%20which%20mysql_real_escape_string()%20may%20have%20inserted%20into%20submissions.

    $grav_url%20creates%20our%20Gravatar%20from%20each%20users%20email%20address.

    We%20then%20output%20(echo)%20each%20shout%20in%20a%20specific%20manner.%20Basically%20displaying%20the%20Gravatar,%20Name%20and%20Shout%20in%20a%20list%20we%20can%20easily%20style%20later.

    The%20Form

    The%20final%20step%20for%20this%20page%20is%20to%20include%20a%20form%20to%20the%20bottom%20of%20the%20page%20which%20users%20can%20submit%20posts%20through.

    view%20plaincopy%20to%20clipboardprint?
    <form action="<?php $self ?>" method="post">  
  • <h2>Shout! </h2>  
  • <div class="fname"><LABEL for=name><P>Name:</p></label><input name="name" type="text" cols="20" /></div>  
  • <div class="femail"><LABEL for=email><P>Email:</p></label><input name="email" type="text" cols="20" /></div>  
  • <textarea name="post" rows="5" cols="40"></textarea>  
  • <input name="send" type="hidden" />  
  • <p><input type="submit" value="send" /></p>  
  • </form>  
  •   
  • </div><!--/content-->  
  • <div id="boxbot"></div>  
  • </div><!--/container-->  
  • </body>  
  • </html>  
  • </P>  
    <form%20action="<?php%20$self%20?>"%20method="post"> <h2>Shout!%20</h2> <div%20class="fname">

    Name:</p></label><input%20name="name"%20type="text"%20cols="20"%20/></div> <div%20class="femail">

    Email:</p></label><input%20name="email"%20type="text"%20cols="20"%20/></div> <textarea%20name="post"%20rows="5"%20cols="40"></textarea> <input%20name="send"%20type="hidden"%20/> <p><input%20type="submit"%20value="send"%20/></p> </form> </div><!--/content--> <div%20id="boxbot"></div> </div><!--/container--> </body> </html>

    Note%20that%20we%20reference%20the%20$self%20variable%20to%20tell%20the%20form%20where%20to%20send%20it's%20results;%20and%20we%20also%20send%20via%20the%20POST%20method.%20Below%20the%20form%20we%20close%20off%20any%20HTML%20tags%20we%20opened.

    Styling

    Try%20it%20out!%20You've%20finished%20all%20the%20PHP%20code,%20and%20you%20should%20be%20able%20to%20add%20a%20new%20shout%20and%20see%20the%208%20latest%20ones.

    However, there's one problem. It looks UGLY! Lets sort that out with some CSS :) With this not being a CSS tutorial, I won't go over any of the styling, but everything's pretty basic.

    view plaincopy to clipboardprint?
    1. * {   
    2. margin: 0;   
    3. padding: 0;   
    4. }   
    5.   
    6. body {   
    7. background#323f66 top center url("images/back.png"no-repeat;   
    8. color#ffffff;   
    9. font-familyHelveticaArialVerdanasans-serif;   
    10. }   
    11.   
    12. h1 {   
    13. font-size: 3.5em;   
    14. letter-spacing: -1px;   
    15. backgroundurl("images/shoutbox.png"no-repeat;   
    16. width303px;   
    17. margin: 0 auto;   
    18. text-indent: -9999em;   
    19. color#33ccff;   
    20. }   
    21.   
    22. h2 {   
    23. font-size: 2em;   
    24. letter-spacing: -1px;   
    25. backgroundurl("images/shout.png"no-repeat;   
    26. width119px;   
    27. text-indent: -9999em;   
    28. color#33ccff;   
    29. clearboth;   
    30. margin15px 0;   
    31. }   
    32.   
    33. h5 a:link, h5 a:visited {   
    34. color#ffffff;   
    35. text-decorationnone;   
    36. }   
    37.   
    38. h5 a:hover, h5 a:active, h5 a:focus {   
    39. border-bottom1px solid #fff;   
    40. }   
    41.   
    42. p {   
    43. font-size: 0.9em;   
    44. line-height: 1.3em;   
    45. font-family: Lucida Sans Unicode, HelveticaArialVerdanasans-serif;   
    46. }   
    47.   
    48. p.error {   
    49. background-color#603131;   
    50. border1px solid #5c2d2d;   
    51. width260px;   
    52. padding10px;   
    53. margin-bottom15px;   
    54. }   
    55.   
    56. p.success {   
    57. background-color#313d60;   
    58. border1px solid #2d395c;   
    59. width260px;   
    60. padding10px;   
    61. margin-bottom15px;   
    62. }   
    63.   
    64. #container {   
    65. width664px;   
    66. margin20px auto;   
    67. text-aligncenter;   
    68. }   
    69.   
    70.     #boxtop {   
    71.     margin30px auto 0px;   
    72.     backgroundurl("images/top.png"no-repeat;   
    73.     width663px;   
    74.     height23px;   
    75.     }   
    76.   
    77.        
    78.     #boxbot {   
    79.     margin0px auto 30px;   
    80.     backgroundurl("images/bot.png"no-repeat;   
    81.     width664px;   
    82.     height25px;   
    83.     }   
    84.   
    85.     #content {   
    86.     margin: 0 auto;   
    87.     width664px;   
    88.     text-alignleft;   
    89.     backgroundurl("images/bg.png"repeat-y;   
    90.     padding15px 35px;   
    91.     }   
    92.        
    93.     #content ul {   
    94.     margin-left: 0;   
    95.     margin-bottom15px;   
    96.     }   
    97.        
    98.     #content ul li {   
    99.     list-stylenone;   
    100.     clearboth;   
    101.     padding-top30px;   
    102.     }   
    103.        
    104.         #content ul li:first-child {   
    105.         padding-top:0;   
    106.         }   
    107.        
    108.     .meta {   
    109.     width85px;   
    110.     text-alignleft;   
    111.     floatleft;   
    112.     min-height110px;   
    113.     font-weightbold;   
    114.     }   
    115.        
    116.         .meta img {   
    117.         padding5px;   
    118.         background-color#313d60;   
    119.         }   
    120.            
    121.         .meta p {   
    122.         font-size: 0.8em;   
    123.         }   
    124.        
    125.     .shout {   
    126.     width500px;   
    127.     floatleft;   
    128.     margin-left15px;   
    129.     min-height110px;   
    130.     padding-top5px;   
    131.     }   
    132.        
    133.     form {   
    134.     clearboth;   
    135.     margin-top135px !important;   
    136.     }   
    137.        
    138.         .fname, .femail {   
    139.         width222px;   
    140.         floatleft;   
    141.         }   
    142.            
    143.         form p {   
    144.         font-weightbold;   
    145.         margin-bottom3px;   
    146.         }   
    147.            
    148.         form textarea {   
    149.         width365px;   
    150.         overflowhidden/* removes vertical scrollbar in IE */  
    151.         }   
    152.        
    153.         form input, form textarea {   
    154.         background-color#313d60;   
    155.         border1px solid #2d395c;   
    156.         color#ffffff;   
    157.         padding5px;   
    158.         font-family: Lucida Sans Unicode, HelveticaArialVerdanasans-serif;   
    159.         margin-bottom10px;   
    160.         }  

    discuss this topic to forum

    relation tutorial

    No information

    Category

      Ad Management (6)
      Calendars (3)
      Chat Systems (8)
      Content Management (41)
      Cookies and Sessions (12)
      Counters (15)
      Database Related (29)
      Date and Time (13)
      Development (19)
      Discussion Boards (8)
      E Commerce (8)
      Email Systems (13)
      Error Handling (7)
      File Manipulation (24)
      Flash and PHP (6)
      Form Processing (19)
      Guestbooks (12)
      Image Manipulation (21)
      Installing PHP (7)
      Introduction to PHP (23)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (53)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot