Wednesday, 26 May 2021

How to Create Review & Rating Page in PHP with Ajax

PHP Review & Rating System using Ajax - Part 1




PHP Review & Rating System using Ajax - Part 2





In this post, you can find How to create product or service review and star rating system with PHP & Mysql using Ajax jQuery. By using Review and Rating Module, user of your website will share their opinion and experiences which are related to your product or services.

Review and Rating System is very important feature for get your user feedback regarding your product or services. With the help of review and star rating system, your user can rate your product or services by selecting star and write review about your product and services and with the help or this review and star rating service provider or product seller can improve their product or services. At the other hand at buyer side, because with the help of product or service rating and review, buyer can select quality product or services based on the rating and review provided by other customers.

We can easily developed our own Rating and Review System with Mysql database using PHP with Ajax & jQuery. If you want to implement Review and Star Rating system for your product or services then this tutorial will help you to build review and 5 star rating system using PHP with Ajax jQuery and Mysql Database.


How to Create Review & Rating Page in PHP with Ajax


In this tutorial, we will build Review and 5 star rating system for single product to demonstrate the functionality and user interface of Review and Rating System. Below you can find the feature of this PHP Dynamic Review and Rating System with Ajax jQuery.

  • View Average Star Rating in Number and on Star icon.
  • View Total Number of Review.
  • View Total Number of Review in 1 to 5 Star with Animated progress bar
  • Submit Review and Rating using Bootstrap 4 ModalM
  • Submit Review and Rating without Refresh of web page using Ajax jQuery.
  • Fetch Review and Rating Data from Database and Display on Web page in Review and Rating format using Ajax with PHP script.
  • At Front-end side we have use Ajax, jQuery and Bootstrap 4 library and at Back-end we have use PHP script and Mysql Database for build this Review and Rating System.




Set Up Database Table


For build any dynamic system we need database and under database we need table. So first need to create database, so here we have already created testing for this tutorial and under this database for create review table, we have to run following .sql script for create review_table in Mysql Database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `review_table`
--

CREATE TABLE `review_table` (
  `review_id` int(11) NOT NULL,
  `user_name` varchar(200) NOT NULL,
  `user_rating` int(1) NOT NULL,
  `user_review` text NOT NULL,
  `datetime` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `review_table`
--

INSERT INTO `review_table` (`review_id`, `user_name`, `user_rating`, `user_review`, `datetime`) VALUES
(6, 'John Smith', 4, 'Nice Product, Value for money', 1621935691),
(7, 'Peter Parker', 5, 'Nice Product with Good Feature.', 1621939888),
(8, 'Donna Hubber', 1, 'Worst Product, lost my money.', 1621940010);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `review_table`
--
ALTER TABLE `review_table`
  ADD PRIMARY KEY (`review_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `review_table`
--
ALTER TABLE `review_table`
  MODIFY `review_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;



Review and Rating System Index Page


For build and Dynamic Review and Rating System, we have to first create layout for display Star Rating and Review data on web page. So in index.php we have to first create HTML code for display and Review and Rating content with Submit Rating and Review Data to the Server.

So here in HTML code part, for display Rating data in Star icon we have use Font Awesome library and for Submit Review and Rating data we have use Bootstrap 4 modal dialog box. Below you can find HTML source code for create layout for display Rating and Review data on web page.

index.php

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8" />
    <title>Review & Rating System in PHP & Mysql using Ajax</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
    	<h1 class="mt-5 mb-5">Review & Rating System in PHP & Mysql using Ajax</h1>
    	<div class="card">
    		<div class="card-header">Sample Product</div>
    		<div class="card-body">
    			<div class="row">
    				<div class="col-sm-4 text-center">
    					<h1 class="text-warning mt-4 mb-4">
    						<b><span id="average_rating">0.0</span> / 5</b>
    					</h1>
    					<div class="mb-3">
    						<i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
	    				</div>
    					<h3><span id="total_review">0</span> Review</h3>
    				</div>
    				<div class="col-sm-4">
    					<p>
                            <div class="progress-label-left"><b>5</b> <i class="fas fa-star text-warning"></i></div>

                            <div class="progress-label-right">(<span id="total_five_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="five_star_progress"></div>
                            </div>
                        </p>
    					<p>
                            <div class="progress-label-left"><b>4</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_four_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="four_star_progress"></div>
                            </div>               
                        </p>
    					<p>
                            <div class="progress-label-left"><b>3</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_three_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="three_star_progress"></div>
                            </div>               
                        </p>
    					<p>
                            <div class="progress-label-left"><b>2</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_two_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="two_star_progress"></div>
                            </div>               
                        </p>
    					<p>
                            <div class="progress-label-left"><b>1</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_one_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="one_star_progress"></div>
                            </div>               
                        </p>
    				</div>
    				<div class="col-sm-4 text-center">
    					<h3 class="mt-4 mb-3">Write Review Here</h3>
    					<button type="button" name="add_review" id="add_review" class="btn btn-primary">Review</button>
    				</div>
    			</div>
    		</div>
    	</div>
    	<div class="mt-5" id="review_content"></div>
    </div>
</body>
</html>

<div id="review_modal" class="modal" tabindex="-1" role="dialog">
  	<div class="modal-dialog" role="document">
    	<div class="modal-content">
	      	<div class="modal-header">
	        	<h5 class="modal-title">Submit Review</h5>
	        	<button type="button" class="close" data-dismiss="modal" aria-label="Close">
	          		<span aria-hidden="true">&times;</span>
	        	</button>
	      	</div>
	      	<div class="modal-body">
	      		<h4 class="text-center mt-2 mb-4">
	        		<i class="fas fa-star star-light submit_star mr-1" id="submit_star_1" data-rating="1"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_2" data-rating="2"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_3" data-rating="3"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_4" data-rating="4"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_5" data-rating="5"></i>
	        	</h4>
	        	<div class="form-group">
	        		<input type="text" name="user_name" id="user_name" class="form-control" placeholder="Enter Your Name" />
	        	</div>
	        	<div class="form-group">
	        		<textarea name="user_review" id="user_review" class="form-control" placeholder="Type Review Here"></textarea>
	        	</div>
	        	<div class="form-group text-center mt-4">
	        		<button type="button" class="btn btn-primary" id="save_review">Submit</button>
	        	</div>
	      	</div>
    	</div>
  	</div>
</div>


Once we have create this html code, next we need to write jQuery for animate star icon, when we have mouse over or mouse leave from star icon. So in below jquery you can find how to animate star icon.



var rating_data = 0;

    $('#add_review').click(function(){

        $('#review_modal').modal('show');

    });

    $(document).on('mouseenter', '.submit_star', function(){

        var rating = $(this).data('rating');

        reset_background();

        for(var count = 1; count <= rating; count++)
        {

            $('#submit_star_'+count).addClass('text-warning');

        }

    });

    function reset_background()
    {
        for(var count = 1; count <= 5; count++)
        {

            $('#submit_star_'+count).addClass('star-light');

            $('#submit_star_'+count).removeClass('text-warning');

        }
    }

    $(document).on('mouseleave', '.submit_star', function(){

        reset_background();

        for(var count = 1; count <= rating_data; count++)
        {

            $('#submit_star_'+count).removeClass('star-light');

            $('#submit_star_'+count).addClass('text-warning');
        }

    });

    $(document).on('click', '.submit_star', function(){

        rating_data = $(this).data('rating');

    });

    $('#save_review').click(function(){

        var user_name = $('#user_name').val();

        var user_review = $('#user_review').val();

        if(user_name == '' || user_review == '')
        {
            alert("Please Fill Both Field");
            return false;
        }
        else
        {
            $.ajax({
                url:"submit_rating.php",
                method:"POST",
                data:{rating_data:rating_data, user_name:user_name, user_review:user_review},
                success:function(data)
                {
                    $('#review_modal').modal('hide');

                    load_rating_data();

                    alert(data);
                }
            })
        }

    });


In this jQuery code, we have create one rating_data variable. Under this variable we will store user star rating data when user has click on any number of star icon.

Next for submit Review and Rating data using bootstrap modal, we have use Ajax request, so when user click on submit button after fill review field, then star rating and review data will be send to PHP server script using Ajax request and this request will also received response from server also.

Insert or Sve Review and Rating System Data


Once user has click on submit button then rating and reive data will be send to PHP script. So at PHP script first we need to make database connection. So below code you can see in which it will make Mysql database connection.

submit_rating.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");


After making database connection, then it will check $_POST["rating_data"] variable value has been set or not. IF this variable value is set then it will store review and rating data in simple array because here we will use PHP PDO class for insert data into database. And next we have write insert query and execute query for insert review and rating data into Mysql database and send response to Ajax request also.


if(isset($_POST["rating_data"]))
{

	$data = array(
		':user_name'		=>	$_POST["user_name"],
		':user_rating'		=>	$_POST["rating_data"],
		':user_review'		=>	$_POST["user_review"],
		':datetime'			=>	time()
	);

	$query = "
	INSERT INTO review_table 
	(user_name, user_rating, user_review, datetime) 
	VALUES (:user_name, :user_rating, :user_review, :datetime)
	";

	$statement = $connect->prepare($query);

	$statement->execute($data);

	echo "Your Review & Rating Successfully Submitted";

}


Fetch Review & Rating Data From Database


Here we have make dynamic Review and Rating System in PHP and Review and Rating data has been store under database. So once data has been store in database. Then we need to fetch from database and display on web page. So Here we have we have use Ajax jQuery for fetch data from database. For Fetch data we will make function which will send ajax request to PHP script and at server side php script will fetch data from database and return back data to Ajax request in JSON format. So once data has been received from server in JSON format then by using jQuery code it will display on web page. It will display both Star Rating and Review data on web page. Below you can find jQuery script and PHP script code for fetch data from database and display on web page without refresh of web page.

index.php

$('#save_review').click(function(){

        var user_name = $('#user_name').val();

        var user_review = $('#user_review').val();

        if(user_name == '' || user_review == '')
        {
            alert("Please Fill Both Field");
            return false;
        }
        else
        {
            $.ajax({
                url:"submit_rating.php",
                method:"POST",
                data:{rating_data:rating_data, user_name:user_name, user_review:user_review},
                success:function(data)
                {
                    $('#review_modal').modal('hide');

                    load_rating_data();

                    alert(data);
                }
            })
        }

    });

    load_rating_data();

    function load_rating_data()
    {
        $.ajax({
            url:"submit_rating.php",
            method:"POST",
            data:{action:'load_data'},
            dataType:"JSON",
            success:function(data)
            {
                $('#average_rating').text(data.average_rating);
                $('#total_review').text(data.total_review);

                var count_star = 0;

                $('.main_star').each(function(){
                    count_star++;
                    if(Math.ceil(data.average_rating) >= count_star)
                    {
                        $(this).addClass('text-warning');
                        $(this).addClass('star-light');
                    }
                });

                $('#total_five_star_review').text(data.five_star_review);

                $('#total_four_star_review').text(data.four_star_review);

                $('#total_three_star_review').text(data.three_star_review);

                $('#total_two_star_review').text(data.two_star_review);

                $('#total_one_star_review').text(data.one_star_review);

                $('#five_star_progress').css('width', (data.five_star_review/data.total_review) * 100 + '%');

                $('#four_star_progress').css('width', (data.four_star_review/data.total_review) * 100 + '%');

                $('#three_star_progress').css('width', (data.three_star_review/data.total_review) * 100 + '%');

                $('#two_star_progress').css('width', (data.two_star_review/data.total_review) * 100 + '%');

                $('#one_star_progress').css('width', (data.one_star_review/data.total_review) * 100 + '%');

                if(data.review_data.length > 0)
                {
                    var html = '';

                    for(var count = 0; count < data.review_data.length; count++)
                    {
                        html += '<div class="row mb-3">';

                        html += '<div class="col-sm-1"><div class="rounded-circle bg-danger text-white pt-2 pb-2"><h3 class="text-center">'+data.review_data[count].user_name.charAt(0)+'</h3></div></div>';

                        html += '<div class="col-sm-11">';

                        html += '<div class="card">';

                        html += '<div class="card-header"><b>'+data.review_data[count].user_name+'</b></div>';

                        html += '<div class="card-body">';

                        for(var star = 1; star <= 5; star++)
                        {
                            var class_name = '';

                            if(data.review_data[count].rating >= star)
                            {
                                class_name = 'text-warning';
                            }
                            else
                            {
                                class_name = 'star-light';
                            }

                            html += '<i class="fas fa-star '+class_name+' mr-1"></i>';
                        }

                        html += '<br />';

                        html += data.review_data[count].user_review;

                        html += '</div>';

                        html += '<div class="card-footer text-right">On '+data.review_data[count].datetime+'</div>';

                        html += '</div>';

                        html += '</div>';

                        html += '</div>';
                    }

                    $('#review_content').html(html);
                }
            }
        })
    }


submit_rating.php

if(isset($_POST["action"]))
{
	$average_rating = 0;
	$total_review = 0;
	$five_star_review = 0;
	$four_star_review = 0;
	$three_star_review = 0;
	$two_star_review = 0;
	$one_star_review = 0;
	$total_user_rating = 0;
	$review_content = array();

	$query = "
	SELECT * FROM review_table 
	ORDER BY review_id DESC
	";

	$result = $connect->query($query, PDO::FETCH_ASSOC);

	foreach($result as $row)
	{
		$review_content[] = array(
			'user_name'		=>	$row["user_name"],
			'user_review'	=>	$row["user_review"],
			'rating'		=>	$row["user_rating"],
			'datetime'		=>	date('l jS, F Y h:i:s A', $row["datetime"])
		);

		if($row["user_rating"] == '5')
		{
			$five_star_review++;
		}

		if($row["user_rating"] == '4')
		{
			$four_star_review++;
		}

		if($row["user_rating"] == '3')
		{
			$three_star_review++;
		}

		if($row["user_rating"] == '2')
		{
			$two_star_review++;
		}

		if($row["user_rating"] == '1')
		{
			$one_star_review++;
		}

		$total_review++;

		$total_user_rating = $total_user_rating + $row["user_rating"];

	}

	$average_rating = $total_user_rating / $total_review;

	$output = array(
		'average_rating'	=>	number_format($average_rating, 1),
		'total_review'		=>	$total_review,
		'five_star_review'	=>	$five_star_review,
		'four_star_review'	=>	$four_star_review,
		'three_star_review'	=>	$three_star_review,
		'two_star_review'	=>	$two_star_review,
		'one_star_review'	=>	$one_star_review,
		'review_data'		=>	$review_content
	);

	echo json_encode($output);

}


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.





Tuesday, 18 May 2021

Submit Form without Page Refresh using JavaScript with PHP

Validate PHP Form Data with JavaScript



Submit PHP Form Data using JavaScript



Under this tutorial, you will learn how to submit a HTML form with form data validation without refresh of webpage by using pure vanilla javascript with Ajax PHP and then after insert HTML form data into Mysql database using Ajax with PHP. In this post you do not need to download jQuery library or do not include jQuery javascript library link at header of your webpage. This is because we will use only javascript so for use javascript in web page, you do not include any library in your webpage because javascript should be included in or referenced by an HTML web page for the code has been interpreted by the browser.

In the current time, there are web traffic has been increase day by day popularity of our website, so at that time we have want to increase our website web experience. So for increase web experience, we have to improve our web application by providing better user experience by optimize our website and reduce traffic to our web application. So for optimize our website, first we want to reduce not necessary web page reload. So for refresh web page reload we have to submit form data without refresh of web page. So this will reduces load on internet to reload entire web page our web application without refresh of web page.

Under this tutorial, for implement form data with validation of form data without refresh of web page using javascript with php. For this here we will create HTML web form and then after we will submit form data without refresh of web page and perform form data validation in background PHP server side process and get response from server back to HTML web page. If there is any validation error has occure, then it will display validation error on web page, and if data successfully inserted, then it will display success message on web page. So this is a great way to improve the user our website user experience of our website and then submit forms with validation without a page refresh. In this post, you can find how to submit form with validation of form data using javascript with PHP script. For this feature we will make sample form with some form field and then after we will submit all form field with PHP script and at PHP script it will validate form data and insert into database without refresh of web page using pure vanilla javascript.


Submit Form without Page Refresh using JavaScript with PHP




Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `data_sample`
--

CREATE TABLE `data_sample` (
  `id` int(11) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL,
  `website` varchar(150) NOT NULL,
  `comment` text NOT NULL,
  `gender` enum('Male','Female') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `data_sample`
--
ALTER TABLE `data_sample`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `data_sample`
--
ALTER TABLE `data_sample`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;





index.html



<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>PHP Form Validation with Vanilla JavaScript</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
    <div class="container">
    	<h2 class="text-center mt-4 mb-2">PHP Form Validation with Vanilla JavaScript</h2>
    	
    	<span id="message"></span>
    	<form id="sample_form">
		   	<div class="card">
		    	<div class="card-header">Sample Form</div>
		    	<div class="card-body">
		    		<div class="form-group">
	    				<label>Name <span class="text-danger">*</span></label>
	    				<input type="text" name="name" id="name" class="form-control form_data" />
	    				<span id="name_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>E-mail <span class="text-danger">*</span></label>
	    				<input type="text" name="email" id="email" class="form-control form_data" />
	    				<span id="email_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>Website <span class="text-danger">*</span></label>
	    				<input type="text" name="website" id="website" class="form-control form_data" />
	    				<span id="website_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>Comment <span class="text-danger">*</span></label>
	    				<textarea name="comment" id="comment" cols="40" rows="5" class="form-control form_data"></textarea>
	    				<span id="comment_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>Gender <span class="text-danger">*</span></label>
	    				<select name="gender" id="gender" class="form-control form_data">
	    					<option value="">Select Gender</option>
	    					<option value="Male">Male</option>
	    					<option value="Female">Female</option>
	    				</select>
	    				<span id="gender_error" class="text-danger"></span>
	    			</div>
		    	</div>
		    	<div class="card-footer">
		    		<button type="button" name="submit" id="submit" class="btn btn-primary" onclick="save_data(); return false;">Save</button>
		    	</div>
		    </div>
		</form>
		<br />
		<br />
    </div>
</body>
</html>

<script>

function save_data()
{
	var form_element = document.getElementsByClassName('form_data');

	var form_data = new FormData();

	for(var count = 0; count < form_element.length; count++)
	{
		form_data.append(form_element[count].name, form_element[count].value);
	}

	document.getElementById('submit').disabled = true;

	var ajax_request = new XMLHttpRequest();

	ajax_request.open('POST', 'process_data.php');

	ajax_request.send(form_data);

	ajax_request.onreadystatechange = function()
	{
		if(ajax_request.readyState == 4 && ajax_request.status == 200)
		{
			document.getElementById('submit').disabled = false;

			var response = JSON.parse(ajax_request.responseText);

			if(response.success != '')
			{
				document.getElementById('sample_form').reset();

				document.getElementById('message').innerHTML = response.success;

				setTimeout(function(){

					document.getElementById('message').innerHTML = '';

				}, 5000);

				document.getElementById('name_error').innerHTML = '';

				document.getElementById('email_error').innerHTML = '';

				document.getElementById('website_error').innerHTML = '';
				document.getElementById('comment_error').innerHTML = '';
				document.getElementById('gender_error').innerHTML = '';
			}
			else
			{
				//display validation error
				document.getElementById('name_error').innerHTML = response.name_error;
				document.getElementById('email_error').innerHTML = response.email_error;
				document.getElementById('website_error').innerHTML = response.website_error;
				document.getElementById('comment_error').innerHTML = response.comment_error;
				document.getElementById('gender_error').innerHTML = response.gender_error;
			}

			
		}
	}
}
	

</script>


process_data.php



<?php

//process_data.php

if(isset($_POST["name"]))
{
	sleep(5);
	$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

	$success = '';

	$name = $_POST["name"];

	$email = $_POST["email"];

	$website = $_POST["website"];

	$comment = $_POST["comment"];

	$gender = $_POST["gender"];

	$name_error = '';
	$email_error = '';
	$website_error = '';
	$comment_error = '';
	$gender_error = '';

	if(empty($name))
	{
		$name_error = 'Name is Required';
	}
	else
	{
		if(!preg_match("/^[a-zA-Z-' ]*$/", $name))
		{
			$name_error = 'Only Letters and White Space Allowed';
		}
	}

	if(empty($email))
	{
		$email_error = 'Email is Required';
	}
	else
	{
		if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		{
			$email_error = 'eMail is invalid';
		}
	}

	if(empty($website))
	{
		$website_error = 'Website is Required';
	}
	else
	{
		if(!filter_var($website, FILTER_VALIDATE_URL))
		{
			$website_error = 'Invalid Website Url';
		}
	}

	if(empty($comment))
	{
		$comment_error = 'Comment is Required Field';
	}

	if(empty($gender))
	{
		$gender_error = 'Please Select your gender';
	}

	if($name_error == '' && $email_error == '' && $website_error == '' && $comment_error == '' && $gender_error == '')
	{
		//put insert data code here 

		$data = array(
			':name'			=>	$name,
			':email'		=>	$email,
			':website'		=>	$website,
			':comment'		=>	$comment,
			':gender'		=>	$gender
		);

		$query = "
		INSERT INTO data_sample 
		(name, email, website, comment, gender) 
		VALUES (:name, :email, :website, :comment, :gender)
		";

		$statement = $connect->prepare($query);

		$statement->execute($data);

		$success = '<div class="alert alert-success">Data Saved</div>';
	}

	$output = array(
		'success'		=>	$success,
		'name_error'	=>	$name_error,
		'email_error'	=>	$email_error,
		'website_error'	=>	$website_error,
		'comment_error'	=>	$comment_error,
		'gender_error'	=>	$gender_error
	);

	echo json_encode($output);
	
}

?>



How To Speed Up WordPress?

How To Speed Up WordPress

Do you want your WordPress website to run faster? These faster pages improve the user experience. It helps in your website and enhances your page views. In this article, we will talk about the most useful WordPress speed optimization to increase the performance of WordPress and speed up your website. Unlike the general "X Tips for Accelerating WordPress" tutorial, this article is a comprehensive guide to WordPress performance optimization.

WordPress has become an overall content management system these days, mainly used by bloggers. Even though the developers have done a great job in improving the speed of WordPress, you can do lots of things to make your blog even faster.

One idea, of course, is to reduce the number of WordPress plugins. And thus, the speed of WordPress has to be increased as well. Generally, people like plugins and many people are using them as well. For example, does a plugin add value to your website? I don't think so because it only shows the visitors who have commented the most frequently, the user who posted the highest number of comments is the website's owner. Because of this, it can be smart to remove the plugin.

We tried to cover everything about why speed is important, what slows down your WordPress site, and actionable steps you can take to quickly improve your WordPress speed. You can also keep a WordPress design agency as they will work for you.

How can you check the speed of your WordPress website?


Often people feel that the speed of their website is excellent. Because she does not run slow on our computer, they think their website is fine, but this is their biggest mistake because you use your website mainly in Chrome. Modern browsers like Chrome keep your website organized as soon as you type anything in it automatically. It automatically loads your website with the prefaces, which you think your website is running very well, but the general user who is coming to your website for the first time, what address to log in to the website with it Problem is coming. Different users have different experiences.

That is why we recommend that you test the speed of your website using (IsItWP) WordPress Speed Test Tool. You can use a free online tool that allows you to train your website speed.

Why is Speed Important for Your WordPress Site?


How To Speed Up WordPress

You have to show your content to users and convince them to stay on your website. You have a lot of work time for this. A slow website means that users will leave your website before it is loaded. Because I am moving very slowly, then the users who are not logging on to your website will open another website because, by the time your website is logged in, they will have gone to another website. You can also hire WordPress developer if you are unable to handle it.

According to the study, which included Amazon, Google, and other sites, a 1 second delay in page load time can lead to 7% reduction in conversions, 11% fewer page views, and a 16% decrease in customer satisfaction. This will never make your website in the ranking. On top of this, Google and other search engines have already pushed you down in search of your website. Your website will be less traffic for slow websites; if you want more customers and traffic to your website, you have to make your WordPress website faster. So that the more traffic on it, the more people load it as soon as they get his result.



What slows down your WordPress website?


How To Speed Up WordPress

You must have several recommendations for improving speed training; many of them are technical term traps that are very difficult for beginners to understand right now. We have to learn what slows down your website to improve it and improve its long run.

The reasons why your website runs slow are:


  • Page size - Some images that are not optimized for the website.
  • Configuration - If your site is not seeing cached pages overloads your server and can cause your website to slow down.
  • External scripts - Ads on External scripts, font loaders can greatly impact your website.
  • Web Hosting - When the web hosting server is not configured correctly, it slows down the speed of your website and can affect the website.
  • Bad plugins - If you are using a plugin with bad code, it can also be very effective on your website.

Speed up WordPress in easy steps


How To Speed Up WordPress

We know that it can be a little difficult for you beginners to change website configuration, and you may have to think a bit to think about it, but you don't have to be afraid of it. We have given thousands of WordPress users their exposure. Help to improve. Let us tell you how you can speed up your website with a few clicks.

1 - Install caching plugin


WordPress pages are "dynamic", it means that whenever someone visits a post on your website, they are immediately ready. WordPress should run a process to find the required information, put it together, and then display it to its user to create its pages. This process involves several steps, and it can slow down your website when you have more than one person coming together. So you should use the WordPress site caching plugin.

When a user visits your WordPress site, your server receives information from a MySQL database and your PHP files. It then aggregates all of them together into HTML. It's a long process, but you can leave a lot of it out when you use caching instead. WordPress hosting companies like SiteGround and Bluehost offer this solution; you can also use them.

2 - Bluehost caching


If you are using Bluehost, visit 'My Sites' to turn on caching. If you are using a WordPress hosting provider, you do not need the caching plugin because it defaults.

3 - Site Ground


If you are using SiteGround, log in to host cPanel and use SuperCacher under 'Site Improvement Tool.' After that, you will need to install and activate the SG Optimizer plugin in WordPress to manage Supercatcher settings.



Importance of good WordPress hosting


How To Speed Up WordPress

Your service plays a vital role in website performance. A good hosting provider like Bluehost or Siteground optimizes your website for display. If there is a lot of traffic to your neighboring site, it can affect the performance of the entire server, which in turn slows down your website. On the other hand, by using WordPress hosting service gives you the most optimized server configuration to run WordPress. These hosting companies also provide automatic backups and more advanced security configurations to protect your website.

This makes your website more likely to get a good ranking. If there is more traffic on another website, your website is not loading correctly, this can reduce your traffic, and your users can use another site. We WPEngine Recommended as Managed WordPress Hosting. They are also the most popular in the industry.

Use a customized theme to increase speed


How To Speed Up WordPress

If you choose a theme for your website, it is essential to keep in mind special things like speed optimization while selecting a theme. Some of the themes look great but look impressive, but when used, it isn't good, and it affects your site, and it slows down your side work by using quality WordPress plugins. You can always add those features. WordPress theme shops like StudioPress, Themify offer themes well optimized for speed. You can also see our article on choosing a suitable WordPress theme for advice on this.

For ranking your website, choose a theme that makes users effective. When selecting a theme, keep in mind the regular things about speed-ups because many themes look very good. But it is also not successful in using, so do not trust every single theme. Some themes are working to a great extent in the market and making their website grow fast. So you too can join in. If you slow down your side box using WordPress plugins, then don't slow it down and introduce a well optimized theme for your speed so that the user is attracted to your site and your website. Give a good ranking too.

Conclusion


You will get information from my given mention, how can you speed up your website, not getting traffic on the right website, and how you will have to bring traffic to your WordPress website, which users will like your website and you get ranking? Get it. You will know how to give ranking to your website and how your website can work at a speed. Because if your rate does not work, your ranking will never get big and your traffic will fall, and Google will block your site, so you know how you will speed up your website.

Authors’ Bio


Nayan serves as a seo executive at comino, where he makes digital marketing strategy and handles all works related to seo, smo and email marketing works and also he gives Resume making tips for job aspirants.


Monday, 17 May 2021

Top 10 PHP Development Tools For Efficient PHP Developers in 2021


PHP is an open-source server-side scripting coding language used for building dynamic websites and web applications. As 79% of total websites, different projects, and systems are built with PHP technology, it remains one of the most popular programming languages globally. It’s applied to create such well-known sites, services, and networks as:

  • Facebook.com;
  • Microsoft.com;
  • Wikipedia.org;
  • Wordpress.com;
  • Vk.com;
  • Zoom.us;
  • Xinhuanet.com, and many more.

If you use PHP to develop web apps and sites, check our top 10 development tools to increase the efficiency of coding and make the work of PHP developers easier.

Top 10 PHP Development Tools


Today there are a lot of development tools available for accelerating the web app development process in a secure manner, including:

  • IDE (Integrated Development Environment);
  • Frameworks:
  • Cloud tools;
  • Data science tools;
  • Source control tools;
  • Prototyping Tools;
  • DevOps Tools;
  • UML Tools.

Such tools help developers not only to build feature-rich innovative projects but to test, debug, maintain designing, fix, and support websites/web apps. Below you’ll find 10 software development tools that allow engineers to streamline and automate some tasks to improve their efficiency and performance.



1. PHPStorm


It’s not by accident that this PHP tool developed and promoted by JetBrains opens the chart. It’s a lightweight, smooth, and extremely fast IDE that works with key PHP frameworks, including but not limited to Laravel, Zend Framework, Symfony, Yii, CakePHP, and supports popular Content Management Systems (CMS) like WordPress, Drupal, Magento, etc.

In addition to code refactoring, unit testing, and debugging, PHPStorm provides live editing support for major frontend technologies (CSS, HTML5, JavaScript, TypeScript, Sass, CoffeeScript, Stylus, Less, etc.). Being the leader in the integrated development environment (IDE) for PHP technology, it equips software engineers with good integration capabilities for databases, remote deployment, command-line tools, version control systems, composer, rest client, and many more.

The key features


  • Code-rearranging;
  • Code completion;
  • Debugging (works with Zend Debugger and Xdebug locally and remotely);
  • Zero-configuration;
  • Support for Native ZenCoding;
  • Support extension with a lot of handy plugins like VimEditor.

Besides PHP, IDE supports such coding languages as JavaScript, Visual Basic, C, C++, and C#. PHPStorm also runs on such popular platforms as Linux, Microsoft Windows, and Mac OS X.

Being free to students and teachers, PHPStorm comes with a license price. Such large brands like Yahoo, Wikipedia, Salesforce, Expedia, Cisco, and others possess the IDE’s licenses.

2. Visual Studio Code


Visual Studio Code (VS Code) is a free and open-source code editor created by Microsoft for such platforms as Windows, macOS, and Linux. Besides PHP, it can be used with a variety of programming languages, including Python, Java, JavaScript, C++, Go, Node.js, T-SQL, C#, .NET Core, HTML, CSS, SCSS, Less, JSON, TypeScript, Markdown, PowerShell, and more.

Here are some of the best features of VS Code:


  • Smart code completion with IntelliSense;
  • Built-in Emmet support;
  • Linting;
  • Debugging;
  • Refactoring;
  • Syntax highlighting;
  • Snippets;
  • Intelligent code completion (autocomplete);
  • Code navigation;
  • Extensibility (developers are allowed to create their own extension);
  • Embedded Git and GitHub integration;
  • Integrated terminal;
  • Live share for pair programming;
  • Full customization from color theme picker and key bindings to integrations and functionality.

3. Docker


The tool takes away repetitive, mundane configuration tasks and can be used throughout the development lifecycle. Docker is a set of PaaS (platform as a service) products that use OS-level virtualization to deliver software in packages called containers that can run on all major platforms including Linux, Windows, or macOS.

Docker can package an app and all its dependencies in containers that are isolated from one another so that you can:

  • Have isolated environments between projects;
  • Test code with different versions;
  • Do both these things with a small footprint.

Containers that have all the virtualization capabilities and use fewer resources than virtual machines make Docker much more lightweight than the traditional virtual machines. Docker allows development teams to:

  • Deliver multiple apps hassle-free;
  • Run all the apps the same way on all the environments (design, testing, staging, production);
  • Deploy the apps in different languages and separate containers independently;
  • Reduce the risk of conflict between languages/libraries/frameworks.

4. PHPUnit


It is a unit testing framework that is an instance of the xUnit architecture. The main goal of this tool is to help developers to reveal the errors in the newly committed code as fast as possible and assert that no code regression has occurred in the codebase. PHPUnit uses assertions to verify that the tested unit is correct and behaves as expected. Therefore, developers can find problems and mistakes early in the development cycle. The test results can be output in different formats like TestDox, JUnit XML, and others.

5. Codeception


Codeception is a multi-featured testing framework that allows writing unit, functional, integration, and acceptance tests in a single, coherent style. All the tests are written in a Behaviour Driven Development (BDD) style — descriptive manner. This means that developers can clearly understand what part of the code is being tested and how it is performed just by taking a look at the test body.

6. PHPStan/Psalm


PHPStan and Psalm are open-source and static analysis tools that can be classified as "Code Review" tools. They are used for improving the quality of the code. Let’s observe the key features.

PHPStan Psalm
  • Catches whole classes of bugs;
  • Focuses on finding errors in the code without actually running it;
  • Moves PHP closer to compiled languages.
  • Identifies both hard-to-spot and obvious bugs in the code that can be missed by a human;
  • Enables developers to take advantage of safe coding patterns;
  • Helps to prevent a lot of type-related runtime errors;
  • Is useful on both small legacy codebases and large ones.


7. XDebug


If you want to improve the performance of your PHP code, reveal the bottlenecks, and increase the development experience, then this extension with a wide range of useful features is what you need to try for sure. XDebug is an extension for PHP that provides debugging and profiling capabilities.

XDebug comes as a PHP extension. It is a tool for profiling and debugging PHP scripts that uses the DBGp debugging protocol and allows developers to quickly localize an error in the code by providing the following information and features:

  • Memory allocation;
  • Tracing: function and stack traces in error messages, including:
    • The function name, file name, line indications;
    • Full parameter display for user-defined functions;
    • Support for member functions;
  • Protection for infinite recursions.

Apart from that, XDebug also delivers:

  • PHP scripts’ profiling information;
  • Code coverage analysis;
  • A debugger front-end so that the developer can debug the scripts interactively.

The extension is also available via the PECL.

8. Bitbucket/GitLab CI/CD


GitLab and Bitbucket can be categorized as Code Collaboration and Version Control tools. Each tool provides a pack of useful features to speed up the development process, making it more efficient. Let’s check what is the main difference between them.

Bitbucket is a PHP development tool that provides software engineers with the ability to:

  • Plan projects;
  • Collaborate on code;
  • Conduct tests;
  • Deploy.

And the highlight of the tool is that all is with free private Git repositories. Besides that, Bitbucket has the following features:

  • Built-in CI/CD;
  • Superior (best-in-class) Jira integration;
  • Up to 5 users can be added for free;
  • Simple setup;
  • Unlimited private repositories, etc.

GitLab is an open-source self-hosted Git management software that can be installed on-premise and connected with LDAP and Active Directory servers for secure authorization and authentication.

The key features of the tool that make it a choice of PHP developers are:

  • A single server handling more than 25,000 users;
  • Several active servers;
  • Git repository management with fine-grained access controls;
  • Provides merge requests for enhancing collaboration and performing code reviews;
  • Activity feeds and wikis;
  • Issue tracking, and many more.

9. Swagger


It’s a Documentation as a Service tool and a dependency-free collection of HTML, Javascript, and CSS assets. Swagger generates interactive OpenAPI documentation for the RESTful API, using doctrine annotations.

The main features of the tool include the following ones:

  • Compatibility with the OpenAPI 3.0 specification;
  • Command-line interface;
  • Ability to extract information from code, existing phpdoc annotations;
  • Exceptional error reporting (with hints, context);
  • Getting started guide.

Such brands as Clever, triGo GmbH, and Hootsuite are already leveraging the benefits of Swagger.

10. Postman


It is a scalable API testing tool and a complete API development environment. It quickly integrates into the CI/CD pipeline and is used for simplifying API workflow in development and testing.

Here are the main reasons to use Postman for your project:

  1. Accessibility: a developer needs to just log in to his/her account to access files anytime, anywhere as long as a Postman app is installed on the PC.
  2. Collections: users are allowed to create collections for their Postman API calls with subfolders as well as multiple requests can be created for each collection for organizing the test suites.
  3. Collaboration: team members can share files easily because collections and environments can be imported/exported.
  4. Environments: developers can not only create different environments but use the same collection for different environments.
  5. Tests: test checkpoints can be added to each Postman API calls to ensure test coverage.
  6. Automation testing: tests can be run in multiple iterations, saving time for repetitive tests.
  7. Debugging: developers can check what data has been retrieved to simplify debug tests.
  8. Continuous Integration: development practices are maintained due to the ability of the tool to support continuous integration.

Bottom line


PHP is one of the most all-inclusive programming languages for web development. However, it’s better to use additional PHP development tools to make the process more efficient. Most of these tools are open-source and provide a wide range of features from syntax highlighting to debugging so that developers can create convenient and scalable code. Just choose the tools that work best for your project and help you improve the development process.


Author

Author's Bio

Bogdan Ivanov is a CTO of DDI development. Bogdan is responsible for building the complete technology strategy within the company. Outlining the company's technological vision, and ensuring that the technological resources are aligned with the company's business needs are his main responsibilities.



7 Essential Magento Security Tips to Protect Your E-commerce store

7 Essential Magento Security Tips to Protect Your E-commerce store


Several brands use Magento to develop and run their e-Commerce stores, making it the second most used e-commerce platform in the world. Though it has a fair share of advantages, a few vulnerabilities exist in terms of security.

A report made by TechRadar states that around 87% of online stores created through Magento have greater exposure to cyberattacks. These attacks can make a website unresponsive and cause a company to lose essential customer details to hackers. As a result, that company’s image may tarnish rapidly and can lose potential clients.

If you operate an online store through Magento and are worried about your website’s security, then follow the steps mentioned below.

Steps to Take to Heighten the Security of Your E-commerce Store


1. Attain an SSL Certificate for Your Online Store


An SSL certificate is a must-have for any website available on the internet. It’s what differentiates between websites that are authentic and secure from those which are insecure. There are several advantages of installing this certificate.

It can improve your website’s SEO rankings, which is an essential role of digital marketing services. Another advantage is that it can boost the confidence of online shoppers to purchase products from your brand.



A Secure Socket Layer (SSL) certificate works to encrypt data traffic that flows in and out of a website. When applied to your e-Commerce website, it can encrypt personal information such as PINs of credit cards, login credentials, etc. This helps in preventing hackers to steal confidential data which can lead to unauthorized transactions or identity frauds.

2. Keep Magento’s version Up-to-Date


Magento is an open-source application, meaning that it regularly receives updates to enhance its functionality. This includes fixing bugs, and renewal of security patches. Regular updates may seem irritating, but they’re important for keeping your online store safe.

Moreover, Magento provides its users with patch notes for every new software version released. These patch notes provide detailed information related to the modifications in the original software, and also inform what weak areas had the developers fixed.

It shows the areas that hackers can take advantage of from those e-Commerce stores using outdated software. So, keeping the e-Commerce platform up to date is a must.

3. Keep a Strong Password for Your Magento Account


Your Magento account’s password is the key to controlling your E-commerce store. If it can be guessed easily, you’ve provided an invitation to online attackers. So, not only your account can be overridden but also one can gain access to all confidential details related to your customers and company data.

To prevent such a situation, it requires making a strong password. Below are a few guidelines for making a strong password.

  • Use a mixture of characters include upper- and lower-case letters, numbers, and special characters.
  • Don’t use the same password for different login portals. If you use the same password for various accounts, higher are the risks of getting your account hacked.
  • Change passwords of several accounts regularly.
  • Store your passwords on the free password manager applications, not on your computer.

4. Scan Your E-Commerce Store through Magento’s scanner


It’s difficult to identify any weaknesses in your online store through mere observation. You require to use the right software that can detect any security vulnerabilities in your website. Luckily, Magento’s creators have introduced free scanning software.

Its features include analyzing whether your website meets the security standards and identifying malicious activity, thus alerting the E-commerce store owner. The security scans can be set on a suitable schedule, and the application allows storing of previous scan reports conducted through Magento. The security scanner also gives free consultation on the correct ways to resolve security issues.

5. Prevent MySQL Injection by Installing a Firewall


SQL injections are a common technique that hackers use to retrieve sensitive information from online websites that take in user credentials. If the attempt becomes successful, attackers can easily gain control over your E-commerce website and steal confidential data ranging from location to credit card numbers and more. Hackers then can easily publicize such information or can conduct unofficial transactions.

Magento has taken precautionary measures to prevent such situations, but it’s recommended to use a firewall application as it can control who can access your website or not. So, it adds a new level of defense to your eCommerce store.



6. Make a Distinct URL path for Your Admin Portal


Your admin portal can be called the control panel of your Magento eCommerce store. Making a strong password is necessary, but it’s even better to enhance the difficulty of your admin page URL.

The basic URL structure of Magento’s admin portal is websitename.com/admin. This can be easily spotted by hackers so they can enter the login site of your Magento account.

Such a risky situation can be avoided by editing the URL path of your website which leads to the admin site. Replace it with such a name that can be only guessed by you. Here is Magento’s guide on enhancing the security of your admin portal for reference.

7. Regularly Backup Your Ecommerce Site


There’s no such thing as a perfect defense system, even though all precautionary measures have been taken. That’s why all E-commerce store owners must regularly take backups of their site. Chances are that your website’s defenses can be compromised, causing you to lose control.

Through backups, you can store the previous versions of your website when it was fully functional. In case your online store becomes unresponsive due to security or compatibility issues, you can restore your website to its previous state. In this way, you and your customers can continue to access your website. You can back up your website on both cloud storage as well as solid-state drives.

Conclusion


Magento’s developers constantly update the e-commerce platform to enhance its functionality and security. However, online businesses need to take every possible measure to ensure the safety of their prospects and their e-commerce stores. Install an SSL certificate that enables the encryption of data traffic to a website.

Make sure that you’ve installed the latest version of Magento’s software and run scans through Magento’s scanning app for finding security issues. By following the above-mentioned tips, you can strengthen the defenses of your e-commerce store.

Author Bio :-


Shaheryar provides ghostwriting and copywriting services. His educational background in the technical field and business studies helps him in tackling topics ranging from career and business productivity to web development and digital marketing. He occasionally writes articles for Dynamologic Solutions.