i

PHP Tutorial

AJAX Database

Above we saw the example of getting the input hints using a PHP file. We can also get the data from the database for AJAX. The webpage will fetch the information from a database with the help of AJAX and give the results on the webpage without refreshing it.

For example: First, we will create a table named comments as below:

create table comments(

           id int(10) not null auto_increment primary_key,

           author text not null,

           message text not null

);

We will manually add comments in the database as below:

insert into comments (author, message) values (‘John’, ‘The product is quite amazing.’);

insert into comments (author, message) values (‘Roy, ‘I love the quality of this product.);

insert into comments (author, message) values (‘John’, ‘It has a beautiful finish.’);

insert into comments (author, message) values (‘Sebastian’, ‘The glass is quite fragile.’);

insert into comments (author, message) values (‘Roy, ‘It is very durable and elegant.’);

Now, we will connect this database to our webpage using database connection.

$servername = “localhost”;

$username = “root”;

$password = “”;

$dbname = “MySQL”;

$conn = mysqli_connect($servername, $username, $password, $dbname);

?>

Now, we will write the code to show the comments.

$sql = SELECT * from comments LIMIT 2;

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) >0) {

           while ($rows = mysqli_fetch_assoc($result))

{

           echo “

”;

           echo $row [‘author’]. “
”;

           echo $row[‘message’]. “

;

 

}

} else {

           echo “No comments”;

}

We need to write this php code inside an HTML form having a button with description Show more comments. The above code will only show first 2 comments. After adding below AJAX code, when we click on show more comments, then two more comments will be loaded without refreshing the page

Load more Comments

The load-comments.php file will have the PHP code we wrote above with a small variation. The LIMIT will be sent through the AJAX code instead of keeping it as LIMIT 2.

$comment_new_count = $POST [‘comment_new_count’];

$sql = SELECT * from comments LIMIT $comment_new_count;

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) >0) {

           while ($rows = mysqli_fetch_assoc($result))

{

           echo “

”;

           echo $row [‘author’]. “
”;

           echo $row[‘message’]. “

;

 

}

} else {

           echo “No comments”;

}

The output of the above code will have 2 comments first, and it will keep on increasing with two more comments without refreshing the page as you click on Load more comments button.