Cara menggunakan script php rating

Setelah selesai mengintsall XAMPP di komputer, selanjutnya Anda sudah bisa memulai membuat website melalui localhost. Langkah pertama yang perlu Anda lakukan adalah membuat file php maupun html di folder htdocs. Lalu apa itu folder localhost htdocs dan bagaimana cara membuat filenya?

Daftar Isi

Seperti yang telah kita ketahui bersama, htdocs merupakan directory root localhost pada XAMPP. Di directory atau folder tersebut, sebuah website bisa dijalankan. Karenanya untuk memudahkan Anda dalam membuat website di localhost, kami akan menjelaskan seluk beluk tentang htdocs dan cara membuat file websitenya di directory tersebut.

Apa itu Folder htdocs?

Cara menggunakan script php rating

Folder htdocs adalah default root directory atau home directory pada xampp. Seluruh data website php atau html (kecuali database) harus ditempatkan di dalam folder ini, agar website Anda bisa diakses. Lokasi folder ini biasanya ada di Windows C > xampp > htdocs.

Untuk lebih mudah dalam mengorganisir project website, sebaiknya Anda membuat folder untuk masing-masing project website. Pada contoh kali ini, website akan dibuat di http://localhost/belajar, sehingga Anda perlu membuat folder baru dengan nama belajar di dalam folder htdocs.

Biasakan membuat folder atau file menggunakan huruf kecil untuk meminimalisir masalah ketika akses website karena masalah case-sensitive pada web server bila nantinya diupload ke server hosting.

Cara menggunakan script php rating

Setelah selesai membuat folder, Anda perlu masuk ke folder belajar dan menempatkan seluruh data-data website di dalam folder belajar tersebut.

Cara menulis file PHP di folder htdocs

Langkah selanjutnya adalah menulis scripts website dalam format html atau php. Pada contoh kali ini, kami akan menggunakan notepad++ yang paling ringan dan mudah digunakan.

Notepad++ merupakan aplikasi source code editor yang gratis dan mendukung banyak bahasa pemrograman. Dengan Notepad++, Anda dengan mudah dan bebas melakukan perubahan kode. Notepad++ bisa didownload melalui link ini.

Berikut contoh scripts php sederhana yang bisa anda coba:

<?php
   echo "belajar PHP menggunakan XAMPP";
   echo "<br />";
   echo "Berhasil!";
?>

Simpan file tersebut dengan nama index.php lalu simpan di folder C:\xampp\htdocs\belajar\

Cara menggunakan script php rating

Cara akses melalui browser

index.php adalah default file yang dibaca oleh webserver untuk ditampilkan pertama kali. Sehingga ketika anda mengakses http://localhost/belajar, maka yang ditampilkan adalah file index.php tersebut, contohnya seperti gambar dibawah ini :

Cara menggunakan script php rating

Pada pembahasan lainnya, kami juga membuat artikel mengenai membuat database yang akan diperlukan bila membuat website dinamis yang bisa dipelajari pada link berikut: Cara membuat database di localhost

Cara mengubah directory root di XAMPP

Pada dasarnya, Anda bisa mengubah lokasi directory root sesuai yang diinginkan. Contohnya Anda ingin mengubah directory awal dari htdocs ke directory D:/website misalnya, hal tersebut bisa saja dilakukan melalui httpd.conf.

Untuk mengubah directory root tersebut, Anda bisa membuka XAMPP Control Panel pada bagian Apache > config > Apache (httpd.conf) seperti gambar di bawah ini:

Cara menggunakan script php rating

Setelah itu, cari bagian DocumentRoot “C:/xampp/htdocs” dan ubah sesuai folder atau directory yang Anda inginkan.

Cara menggunakan script php rating

Setelah selesai mengubah directory-nya, jangan lupa untuk restart service apache pada XAMPP agar perubahan bisa berjalan.

Demikian artikel kami tentang cara menjalankan script website di localhost htdocs pada aplikasi XAMPP. Semoga dengan panduan ini, Anda semakin mudah untuk membuat website di localhost.

Bagi Anda yang telah selesai membuat website di localhost dan ingin agar website bisa diakses secara online, Anda bisa memesan domain dan hosting di Rumahweb. Tersedia ratusan ekstensi domain dan promo hosting murah yang bisa Anda pilih.

How do you know your readers’ or customers’ thoughts on your website content? How does the star rating feature help to collect customers’ opinions?

Star rating is a feature that is used across different domains in a variety of ways. For example, it is one of the key building blocks in an eCommerce website.

Star rating helps you to know how people rank your content. It not only gives rank on your content. Also, it brings more readers to your page by the gained rating.

When you build a website, if you have got scope for implementing a star rating system and you should definitely experiment with it.

Websites use a variety of ways to allow users to rate content. For example, star rating, up-down rating, emoji rating and more.

Cara menggunakan script php rating

We have seen so many examples for star rating, emoji rating and more. I grouped all those in this one single example.

I supported three UI alternatives for the rating section. Those are,

  • Five-star rating
  • Favorite rating
  • Emoji rating

I created a directive in PHP to configure the template for the rating appearance.

What is inside?

Existing plugins to implement a dynamic star rating

There are various plugins available in the market to enable star rating. The ready-made plugins are with enormous features.

For example, Rateit is a jQuery based star rating plugin. It allows embedding a star rating with a list, select and more HTML markup. It supports Font Awesome, Material icons to display rating icons.

The UpvoteJS is a JavaScript package to render a StackExchange-like rating widget.

If you are having a WordPress website, there are built-in rating plugins available. Wp-PostRatings is a popular plugin to implement rating.

Advantages of creating a custom star rating script

With a custom star rating, we can simplify the code logic instead of stuffing a lot.

And thereby, it will make it easy at the time of enhancement or maintenance phase.

It rectifies your overload with a feature-packed built-in. Also, it reduces your effort on managing a thousand lines of code for this simple UI feature.

Various types of rating options

Websites use a different type of rating options to get user’s reviews. The following list shows some of the types.

  • Single or multiple star rating
  • Facebook-like emoji rating
  • Simple up-down voting.
  • Like-unlike rating
  • Bar rating

The types are veries in user’s mindset while rating. For example, the like-unlike and up-down rating expects binary options 0 or 1 from the user. But with the bar rating, it can have a range of points out of some limit.

Star rating example with AJAX

I have created an AJAX-based star rating example code with PHP and jQuery.

This code will show a list of courses with an option to rate each course. The courses are from the database.

The rating element in the UI is configurable. I provided three UI alternatives for the rating section. Star, favorite and emoji ratings are there to collect users’ reviews.

While adding the rating, the code sends it to the PHP via AJAX. Then, it saves the ratings in the MySQL database.

Once rated, the user cannot rerate a course again to avoid duplicate ratings.

The following figure shows the file strucuture of the example code.

Cara menggunakan script php rating

The rating example database

This section shows the structure and the SQL of the database used in this example.

I have created two tables tbl_courses and tbl_course_rating. The tbl_cources database table contains courses on which the user will add ratings.

The tbl_cource_rating table has the mapping with the tbl_cource database. It has a unique rating without duplicates.

Cara menggunakan script php rating

The below script shows the CREATE statement and the data dump for these two tables. By importing this script, you can setup this example in the local environment.

sql/db_rating.sql

--
-- Database: `db_rating`
--

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

--
-- Table structure for table `tbl_course`
--

CREATE TABLE `tbl_course` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `period` varchar(255) NOT NULL,
  `availabe_seats` int(11) NOT NULL,
  `last_date_to_register` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_course`
--

INSERT INTO `tbl_course` (`id`, `name`, `description`, `period`, `availabe_seats`, `last_date_to_register`) VALUES
(1, 'Professional Training for Finantial Analyst\r\n', 'Professional Training for Finantial Analyst', '30 days', 2, '2020-01-31'),
(2, 'Enterprise Programming in Artificial Intelligence\r\n', 'Enterprise Programming in Artificial Intelligence', '30 days', 2, '2020-01-24');

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

--
-- Table structure for table `tbl_course_rating`
--

CREATE TABLE `tbl_course_rating` (
  `id` int(11) NOT NULL,
  `course_id` int(11) NOT NULL,
  `member_id` int(11) NOT NULL,
  `rating` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_course`
--
ALTER TABLE `tbl_course`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `tbl_course_rating`
--
ALTER TABLE `tbl_course_rating`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=95;
COMMIT;

UI design to render star rating option

In a landing page, it shows the list of courses from the database. The HTML code for this page is below.

It loads the rating element based on the PHP constant defined in a common configuration file.

The rating element will show clickable 5-stars or favorite-icons or emoji icons.

On clicking the rating element, it invokes a jQuery script to send AJAX requests to save ratings.

index.php





Star Rating Script in PHP






 

Star Rating Script in PHP

I created separate template files to have different types of rating UI. Those are star-rating-view.php, favorite-rating-view.php and emoji_rating_view.php.

The template files show the onClick event handling specification in the markup.

star-rating-view.php


  • Cara menggunakan script php rating
  • Cara menggunakan script php rating
  • favourite-rating-view.php

    
    
  • Cara menggunakan script php rating
  • Cara menggunakan script php rating
  • In the emoji rating template, it shows a range of five emotion icons from very-sad to very-happy.

    If you are providing support on the user’s queries, you can use the emoji rating. Embedding the emoji rating will give the customer’s emotional feel on your support.

    emoji-rating-view.php

    
                        
  • Cara menggunakan script php rating
  • Cara menggunakan script php rating
  • CSS Styles created for the star rating UI

    assets/css/star-rating-style.php

    ul {
    	margin: 0px;
    	padding: 10px 0px 0px 0px;
    	display: inline-flex;
    }
    
    li.star {
    	list-style: none;
    	display: inline-block;
    	margin-right: 5px;
    	cursor: pointer;
    	color: #9E9E9E;
    }
    
    .row-title {
    	font-size: 20px;
    	color: #232323;
    }
    
    .review-note {
    	font-size: 12px;
    	color: #999;
    	font-style: italic;
    }
    
    .row-item {
    	margin-bottom: 20px;
    	border-bottom: #F0F0F0 1px solid;
    }
    
    p.text-address {
    	font-size: 12px;
    }
    
    img {
    	height: 20px;
    	width: 20px;
    }
    
    .course-detail {
    	font-size: 1em;
    	margin-right: 20px;
    }
    
    .loader-icon {
    	display: none;
    }
    .response {
        display: inline-block;
        vertical-align: super;
        margin-left: 10px;
        color: #FF0000;
    }
    

    jQuery functions to handle user rating action

    This file contains jQuery functions to prepare AJAX requests to save user ratings.

    It also handles the mouse hover events to highlight the rating element. The mouseOverRating() function highlights the star or other rating elements on hovering.

    Similarly, mouseOutRating() resets the rating UI back to its original form on mouse out.

    The AJAX code in the addRating() prepares the request with PHP endpoint URL and data params.

    It receives the server response in the AJAX success callback at which it updates the UI accordingly.

    assets/js/rating.js

    function mouseOverRating(courseId, rating, appearance) {
    	if (appearance == "star") {
    		for (var i = 1; i <= rating; i++) {
    			$('#' + courseId + "_" + i + ' img').attr('src',
    					"./img/" + appearance + "-filled.png");
    		}
    	} else {
    		ratingIconPrefix = "./img/" + appearance;
    		for (var i = 1; i <= rating; i++) {
    			if (appearance == "emoji") {
    				ratingIconPrefix = "./img/" + appearance + "1";
    			}
    			if (i == rating) {
    				$('#' + courseId + "_" + i + ' img').attr('src',
    						ratingIconPrefix + "-filled.png");
    			}
    		}
    	}
    }
    
    function mouseOutRating(courseId, userRating, appearance) {
    	var ratingId;
    	if (appearance == "star") {
    		if (userRating != 0) {
    			for (var i = 1; i <= userRating; i++) {
    				$('#' + courseId + "_" + i + ' img').attr('src',
    						"./img/" + appearance + "-filled.png");
    			}
    		}
    		if (userRating <= 5) {
    			for (var i = (userRating + 1); i <= 5; i++) {
    				$('#' + courseId + "_" + i + ' img').attr('src',
    						"./img/" + appearance + "-open.png");
    
    			}
    		}
    		$(".selected img").attr('src', "./img/" + appearance + "-filled.png");
    	} else {
    		ratingIconPrefix = "./img/" + appearance;
    
    		if (userRating <= 5) {
    			for (var i = 1; i <= 5; i++) {
    				if (appearance == "emoji") {
    					ratingIconPrefix = "./img/" + appearance + i;
    				}
    				if (userRating == i) {
    					$('#' + courseId + "_" + i + ' img').attr('src',
    							ratingIconPrefix + "-filled.png");
    				} else {
    					$('#' + courseId + "_" + i + ' img').attr('src',
    							ratingIconPrefix + "-open.png");
    				}
    			}
    		}
    		var selectedImageSource = $(".selected img").attr('src');
    		if (selectedImageSource) {
    			selectedImageSource = selectedImageSource.replace('open', "filled");
    			$(".selected img").attr('src', selectedImageSource);
    		}
    	}
    }
    
    function addRating(currentElement, courseId, ratingValue, appearance) {
    	var loaderIcon = $(currentElement).closest(".row-item");
    	$.ajax({
    		url : "ajax-end-point/insertRating.php",
    		data : "index=" + ratingValue + "&course_id=" + courseId,
    		type : "POST",
    		beforeSend : function() {
    			$(loaderIcon).find("#loader-icon").show();
    		},
    		success : function(data) {
    			loaderIcon = $(currentElement).closest(".row-item");
    			$(loaderIcon).find("#loader-icon").hide();
    			if (data != "") {
    				$('#response-' + courseId).text(data);
    				return false;
    			}
    			if (appearance == 'star') {
    				$('#list-' + courseId + ' li').each(
    						function(index) {
    							$(this).addClass('selected');
    							if (index == $('#list-' + courseId + ' li').index(
    									currentElement)) {
    								return false;
    							}
    						});
    			} else {
    				$(currentElement).addClass('selected');
    			}
    		}
    	});
    
    }
    

    Storing user rating to MySQL database from PHP

    When the AJAX script called, it prepares a request to the PHP. In PHP, it receives the chosen rating post data and stores it in the rating database.

    Though the UI displays different elements, the rating value ranges from 1 to 5. In the database, it has the mapping between the rating value, course id and member id.

    The below configuration is for setting the rating element appearance. The possible values are there with a comment statement.