1

Guestbook – php example code

This article show php code of simple guestbook with adding post, remove latest post and form reset functionality. All content of article is saved in database.

Guestbook is a simple php application with ability:

  • Post user commit into guestbook – data are stored in mariadb/ mysql database
  • Remove latest user post – latest message in form is used for matching database row in DELETE sql query
  • Reset button reinitialize all displayed messages in space of submit form (upper part of page)

Next picture show final state of our aplication

Guestbook – GUI of application

Basic prerequisities

Before creating our application, we must consider all requirements for data stored in database.

Our database table Guestbook will store:

  • id (uniqe self incrementing number)
  • name_of_writer – text up to 30 chars,
  • write_date – date/ time type generated by script along current time
  • email – text up to 70 chars,
  • message_text – large text with minimal 65 535 chars.

For firstime database and table creation was used phpMyAdmin in XAMPP environment.

Setup data for database access are:

server: localhost or 127.0.0.1

database: test

name: admin

password: test*555

Database and user account is created in phpMyAdmin and first result is shown on next picture.

For quick database table creation we prepared php script with name createdatabase.php with content:

<?php // script for accessing database and first table structure establishement
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user ‚root‘ with no password) */
$dbc = mysqli_connect(„localhost“, „admin“, „test*555“, „test“);
 
// Check connection
if($dbc === false){
    die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
}
 
// Attempt create table query execution
$sql = „CREATE TABLE guestbook(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name_of_writer VARCHAR(30) NOT NULL,
    write_date DATETIME NOT NULL,
    email VARCHAR(70) NOT NULL, /*  UNIQUE removed because posts with same e-mails must be anabled */
    message_text TEXT
)“;
 
if(mysqli_query($dbc, $sql)){
    echo „Table created successfully.“;
} else{
    echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
}
 
// Close connection
mysqli_close($dbc);
?>

After sucessfull run of script can be obtained message:

Form part of the main application page

Form part consist from input fields and one big textarea for input of text message.

 <form method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
          <div class=“form-group“>
              <label>Please provide Your name:</label>
              <input type=“text“ name=“name“ class=“form-control“ value=“<?php echo isset($_POST[‚name‘]) ? $name : ‚Your Name‘; ?>“>
          </div>
          <div class=“form-group“>
            <label>E-mail:</label>
            <input type=“text“ name=“email“ class=“form-control“ value=“<?php echo isset($_POST[‚email‘]) ? $email : ‚e-mail‘; ?>“>
          </div>
          <div class=“form-group“>
            <label>Your message for Guestbook:</label>  <!– textera for input large text –>
            <textarea id=“postmessage“ name=“postmessage“ class=“form-control“ rows=“6″ cols=“50″><?php echo isset($_POST[‚postmessage‘]) ? $postmessage : ‚Your text goes here …‘; ?></textarea>
          </div>
     
          <button type=“submit“ name=“submit“ class=“btn btn-warning“> Send your post </button>
          
          <button type=“submit“ name=“delete“ class=“btn btn-danger“> Delete latest message </button>
          <button type=“submit“ name=“reset“ class=“btn btn-info“> Reset form </button>
          <?php   //($is_result == „true“) ? {          
                
                 if ($is_result ) {
                    
                 echo „<br> <br>“;
                 echo “ <table class=\“table table-success\“> „;
                 echo “ <tr>
                               <td><h5> <em> Yours currently written text is: </em>$postmessage</h5> <td>
                              </tr> „; 
                              echo “ </table> „;
                   
                } ; 
                 ?>
                 <br>
        
      </form>

PHP code for submitted data

After submitting of form data take place these operations:

  • check of presence data in all fields of form – name, e-mail and message
  • validation of e-mail
  • preparation of e-mail to page admin about adding post in to a guestbook
  • inserting data with INSERT query in to a Gusetbook table of test database
  • messaging about success or failure during above mentioned operations

This code follow:

// Control if data was submitted
    if(filter_has_var(INPUT_POST, ‚submit‘)){
        // Data obtained from $_postmessage are assigned to local variables
        $name = htmlspecialchars($_POST[‚name‘]);
        $email = htmlspecialchars($_POST[‚email‘]);
        $postmessage = htmlspecialchars($_POST[‚postmessage‘]); 
        
        $is_result = „true“;
        // Controll if all required fields was written
        if(!empty($email) && !empty($name) && !empty($postmessage)){
            // If check passed – all needed fields are written
            // Check if E-mail is valid
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
                // E-mail is not walid
                $msg = ‚Please use a valid email‘;
                $msgClass = ‚alert-danger‘;
            } else {
                // E-mail is ok
                $toEmail = ‚ciljak@localhost.org‘; //!!! e-mail address to send to – change for your needs!!!
                $subject = ‚Guestbook entry from ‚.$name;
                $body = ‚<h2>To your Guestbook submitted:</h2>
                    <h4>Name</h4><p>‘.$name.'</p>
                    <h4>Email</h4><p>‘.$email.'</p>
                    <h4>Message</h4><p>‘.$postmessage.'</p>
                ‚;
                // Email Headers
                $headers = „MIME-Version: 1.0″ .“\r\n“;
                $headers .=“Content-Type:text/html;charset=UTF-8″ . „\r\n“;
                // Additional Headers
                $headers .= „From: “ .$name. „<„.$email.“>“. „\r\n“;
                // !!! Add entry to the database 
                   // insert into databse 
                        // make database connection
                        $dbc = mysqli_connect(„localhost“, „admin“, „test*555“, „test“);
 
                        // Check connection
                            if($dbc === false){
                                die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                            }
                        
                        // INSERT new entry
                        $date = date(‚Y-m- H:i:s‘); // get current date to log into databse along postmessage written
                        $sql = „INSERT INTO guestbook (name_of_writer, write_date, email, message_text)                   VALUES (‚$name‘, ‚$date‘, ‚$email‘ , ‚$postmessage‘)“;
                        if(mysqli_query($dbc, $sql)){
                            
                            $msg = ‚postmessage sucessfully added to database.‘;
                            $msgClass = ‚alert-success‘;
                        } else{
                            
                            $msg = „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
                            $msgClass = ‚alert-danger‘;
                        }
                        // end connection
                            mysqli_close($dbc);
                if(mail($toEmail, $subject, $body, $headers)){
                    // Email Sent
                    $msg .= ‚Your postmessage was sucessfully send via e-mail‘;
                    $msgClass = ‚alert-success‘;
                } else {
                    // Failed
                    $msg = ‚Your postmessage was not sucessfully send via e-mail‘;
                    $msgClass = ‚alert-danger‘;
                }
            }
        } else {
            // Failed – if not all fields are fullfiled
            $msg = ‚Please fill in all contactform fields‘;
            $msgClass = ‚alert-danger‘;  // bootstrap format for allert message with red color
        }
    };  

PHP code for last entry data delete

Simple delete functionality for current post is creted by removing row witch matching message asi in current submitted article. Solution follow

// if delete button clicked
    if(filter_has_var(INPUT_POST, ‚delete‘)){
            $msg = ‚Delete last mesage hit‘;
            $msgClass = ‚alert-danger‘;  // bootstrap format for allert message with red color
        
            //delete from databse 
            // make database connection
            $dbc = mysqli_connect(„localhost“, „admin“, „test*555“, „test“);
            // Check connection
                if($dbc === false){
                    die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                }
            
            // DELETE last input by matching your written message
               // obtain message string for comparison
               $postmessage = htmlspecialchars($_POST[‚postmessage‘]); 
               $postmessage = trim($postmessage); // trim possible leading whitespaces
               // create DELETE query
               $sql = „DELETE FROM guestbook WHERE message_text = „.“‚$postmessage'“ ;
                if(mysqli_query($dbc, $sql)){
                    
                    $msg = ‚Last message sucessfully removed from database.‘;
                    $msgClass = ‚alert-success‘;
                    // clear entry fileds after sucessfull deleting from database
                    $name =“;
                    $email =“;
                    $postmessage = “; 
                } else {
                    
                    $msg = „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
                    $msgClass = ‚alert-danger‘;
                }
            // end connection
                mysqli_close($dbc);
    };

PHP code for form reset

In some case is good way to reset all error messages displayed in form area. Following code is handy

// if reset button clicked
    if(filter_has_var(INPUT_POST, ‚reset‘)){
        $msg = “;
        $msgClass = “; // bootstrap format for allert message with red color
        $name = “;
        $email = “;
        $postmessage = “;
    };

Outputting article stored in the database in to a Guestbook

Solution for displaying all post messages stored in a database is this. Use SELECT query SELECT * FROM guestbook ORDER BY id DESC. Last part order data in descending manner for showing latest article as first.

Then store result in output variable and fetch them row by row with while loop as it show next code:

<?php  // script for accessing database for all records and then output them in page
            /* Attempt MySQL server connection. Assuming you are running MySQL
            server with default setting (user ‚root‘ with no password) */
            $dbc = mysqli_connect(„localhost“, „admin“, „test*555“, „test“);
            
            // Check connection
            if($dbc === false){
                die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
            }
                                
            // read all rows (data) from guestbook table in test database
            $sql = „SELECT * FROM guestbook ORDER BY id DESC„;  // read in reverse order – newest article first
/*******************************************************************/
/*   Output in form of Article – solution 2 – for Guestbook functionality  */        /*******************************************************************/
            // if data properly selected from guestbook database table
            if($output = mysqli_query($dbc, $sql)){
                if(mysqli_num_rows($output) > 0)
                     {   // if any record obtained from SELECT query
                    
                    // create Guestbook articles on page
                    
                    echo „<h4>Our cutomers written into the Guestbook</h4>“;
                    echo „<br>“;
                    while($row = mysqli_fetch_array($output)) {  //next rows outputed in while loop
                        
                   // echo „<td>“ . $row[‚id‘] . „</td>“;  //id is not important for common visitors
                     echo “ <div class=\“guestbook\“> “ ;
                     echo „<h4>“ .“<b>From: </b>“ . $row[‚name_of_writer‘] . „</h4>“;
                     echo „<h6>“ .“<b>Date of postmessage: </b>“ . $row[‚write_date‘] . „</h6>“;
                     echo „<h5>“ .“ <b>E-mail of sender: </b>“ . $row[‚email‘] . „</h5>“;
                     echo „<p id=\“guestbooktext\“>“ . “  <b>Text of the message: </b> <em>“ . $row[‚message_text‘] . „</em></p>“;
                            //echo „<br>“;
                     echo “ </div> “ ;
                     echo “ <div class=\“guestbookbreak\“> “ ;
                         echo „<br>“;
                      echo “ </div> “ ;
                    }
                    echo „<br>“;
                    // Free result set – free the memory associated with the result
                    mysqli_free_result($output);
                } else {
                    echo „There is no postmessage in Guestbook. Please wirite one.“; // if no records in table
                }
            } else {
                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
            }
            // Close connection
            mysqli_close($dbc);
            ?>

Full code for further study can be obtained from github here.