PSYCHOCODES

Guest Book Application using PHP, MySQL and AJAX

Guest Book Application is a good way to know the opinion of your Website viewers as they can share their reviews on your blog or website so in this tutorial, we are going to build a Simple Guest Book Application using PHP and MySQL and with a little bit touch of AJAX so let's get Started.

Recommended: How to Make a Web Crawler Application in PHP

Before Coding anything let's create the database for our guestbook in which all the comments are going to be stored, just execute the below SQL queries to create a database named 'guestbook' which is having a table 'comments'.

>> create database guestbook;


>> create table comments(
     id int primary key auto_increment,
     comment varchar(500));

Now we have successfully created our database, now let's create a script to connect our PHP code with our database(which we have previously created). Create a new file called connection.php and add the following code into it.

<?php

$host = "localhost"; //modify if this is not your host name
$user = "root";
$db = "guestbook";
$conn = new mysqli($host,$user,"",$db);

?>

Now we will create a PHP script to insert the data into the database and to show the records from the database. Create a file named "insert_comments.php" and add the following code into it.

<?php
include("connection.php");

function show_comments($conn){
    $sql = "select * from comments order by id desc";
    $stmt = $conn->stmt_init();
    if($stmt->prepare($sql)){
        $stmt->bind_result($id,$comment);
        $stmt->execute();
        $stmt->store_result();
        while($stmt->fetch()){
            echo "<div class='comment'>";
            echo $comment;
            echo "</div>";
        }
    }
}

if(isset($_GET['data'])){
    $data = $_GET['data'];
    $stmt = $conn->stmt_init();
    $sql = "INSERT INTO comments VALUES(null,?)";
    if($stmt->prepare($sql)){
        $stmt->bind_param("s",$data);
        if($stmt->execute()){
            show_comments($conn);
        }
    }
}
?>

In the above code, we have created a show_comments() function which will show all the records store in the comments table. 

Now we have completed about 70% of the work but still, 30% is remaining which is our AJAX code and our CSS code. so let's create a new file called "ajax.js" and add the following code into it.

function addComment(){
    try{
        xmlhttp = new XMLHttpRequest();
    }
    catch(e){
        alert("Not Supported");
    }
    var display = document.getElementById("comments-wrapper");
    var data = document.getElementsByTagName("textarea")[0].value;
    if(data==""){
        alert("Please Fill the all the fields");
    }
    else{
    var serverpage = "insert_comments.php?data="+data;
    xmlhttp.open("GET",serverpage);
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            display.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
    }
}

The above code will send and receive all the requests and responses to the server asynchronously to access our insert_comments.php file.

AJAX is a technique to use the JavaScript's XMLHttpRequest object to send a request to the web server Asynchronously or you can say without refreshing the Web page.

Now we have done all the dirty work now it's time to design the UI of our application, create a new file called index.ph and add the following code into it.

<?php
include("insert_comments.php");
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Guest Book Application</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
    <script type="text/javascript" src="ajax.js"></script>
</head>
<body>
   <div id="main-wrapper">
        <div id="inner-wrapper">
            <div id="form-wrapper">
                <textarea></textarea>
                <input type="button" name="comment" value="Comment" onclick="addComment();" />
            </div>
            <div id="comments-wrapper">
                <?php show_comments($conn); ?>
            </div>
        </div>
   </div>
</body>
</html>

We have build up the frame but it is very boring, so let's add a little bit of styling to it, create a new file "style.css" in the same directory and add the following CSS code into it.

body{
    padding:0;
    margin:0;
}
textarea{
    width:100%;
    height:200px;
    border-radius: 5px;
    font-size: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    outline:none;
}
textarea:focus{
    border:1px solid brown;
}
#comments-wrapper{
    width:100%;
    padding: 10px 0 0 0;
}
.comment{
    padding:10px;
    background:lightcyan;
    color:#1c1c1c;
    border:2px solid #1c1c1c;
    font-size: 20px;
    margin:10px auto 10px auto;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
input[type="button"]{
    cursor: pointer;
    border:none;
    padding:10px;
    color:white;
    background: royalblue;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    border-radius: 5px;
}
input[type="button"]:hover{
    background: #1c1c1c;
}
#main-wrapper{
    max-width:700px;
    width:100%;
    margin:auto;
}
#inner-wrapper{
    padding:20px;
}

Congrats you have successfully created a modern day GuestBook application, Try adding some new features into it like the person's name who had commented, comment time etc. 

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.

Share your thoughts