Wednesday, September 18, 2024
HomePHPEasy HTML 5 star score code

Easy HTML 5 star score code


by Vincy. Final modified on March twenty fifth, 2024.

This tutorial provides code to show a 5 star score choice in HTML. The HTML view reveals a question-answer mannequin with a clickable 5 star score.

In a earlier article, we’ve got seen the right way to create a PHP star score system in JavaScript. This tutorial instance creates a dynamic star score for a solution listing from the database.
View demo

Steps so as to add a 5 star score HTML to a question-answer listing

  1. Show the query with a listing of solutions.
  2. Present a mean score out of 5 stars.
  3. Add a clickable 5 star score code to every reply.
  4. Spotlight stars on hover, on click on occasions through JavaScript.
  5. Insert or replace the HTML star score on choose.

HTML Star Rating Output

1. Show query with listing of solutions

This step is to show the information for which the star score is relevant. This HTML code shows the query and solutions to the net web page.

It has a textarea to permit inserting extra solutions to the query.

index.php

<?php
ini_set("display_errors", 1);
require_once __DIR__ . '/lib/QAModel.php';
$userId = 3; // Exchange it with the authenticated person id

$QAModel = new QAModel();
$questionResult = $QAModel->getQuestion();
$questionId = $questionResult[0]["id"];

$answersResult = $QAModel->getAnswer();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Easy HTML 5 star score code</title>
</head>

<physique>
    <div class="phppot-container">
        <h1>Easy HTML 5 star score code</h1>
        <h2>
            <?php echo $questionResult[0]['question']; ?>
        </h2>
        <?php require_once __DIR__ . '/answer-form.php'; ?>

        <?php require_once __DIR__ . '/answer-list.php'; ?>

</physique>
<script src="https://phppot.com/php/html-star-rating/score.js"></script>

</html>

On submitting the shape so as to add new reply, it inserts the file and shows the solutions in a descending order.

answer-form.php

<type technique="submit">
    <div class="row">
        <label for="reply"> Enter your reply:</label>
        <textarea identify="reply" id="reply" rows="6" class="full-width" required></textarea>
    </div>
    <div class="row">
        <enter kind="submit" identify="submit_answer" worth="Submit your reply">
    </div>
    <p class="validation-message" id="demo"> </p>
</type>

2. Present common score out of 5 stars

This code iterates the answerResult array from the database. It reveals the typical score added for the reply out of 5 stars.

The $starCount variable reveals the typical score of a file. And the userRatingCount is score given the reply by the present person.

On this instance it hardcodes a userId variable which is the place to plug in your authentication.

answer-list.php

<div class="answer-list">
    <h2>Solutions:</h2>
    <?php
    if (!empty($answersResult)) {
        foreach ($answersResult as $row) {
            $userRatingCount = 0;
            $userRating = $QAModel->getUserRating($row['id'], $userId);
            if (!empty($userRating)) {
                $userRatingCount = $userRating[0]["star_count"];
            }
    ?>
            <div class="row answer-row">
                <div class="reply">
                    <?php echo $row['answer']; ?>
                </div>
                <div>
                    <img src="https://phppot.com/php/html-star-rating/photographs/star.svg" class="star-view">
                    <?php
                    $starCount = spherical($row["average_star_count"], 1);
                    echo $starCount . "/5";

                    require __DIR__ . "/star-rating-html.php";
                    ?>

                </div>
            </div>
    <?php
        }
    }
    ?>
</div>

3. Add clickable 5 star score code to every reply

The above answer-list.php file consists of this  5 star score HTML. A container shows svg icon for stars by operating a loop with size 5.

The SVG tag has the selectors and occasion callback attributes to set off mouse occasions.

On clicking the HTML star, it units it highlighted and submit the chosen score to PHP.

star-rating-html.php

<div class="rating-container">
    <?php
    for ($i = 1; $i <= 5; $i++) {
        $starClassName = "";
        if ($i <= $userRatingCount) {
            $starClassName = "crammed";
        }
    ?>
        <svg xmlns="http://www.w3.org/2000/svg" width="32" peak="32" viewBox="0 0 24 24" class="star-link <?php echo $starClassName; ?>" stroke-width="1" stroke-linecap="spherical" stroke-linejoin="spherical" class="feather feather-star" onclick="setRating(this, <?php echo $row['id']; ?>, <?php echo $i; ?>)">
            <polygon factors="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
        </svg>
    <?php
    } ?>
</div>

4. Spotlight stars on hover, on click on occasions through JavaScript

This permits highlighting the celebs on choose or on hover the HTML icon. It permit to show the star icon to be crammed with a yellow background.

The setRating() perform is added to the onClick attribute of the star score icons within the HTML code.

On doc prepared, the jQuery occasion registration for the star-link hover impact is proven beneath.

score.js

perform setRating(starIcon, answerId, score) {
    $(starIcon).dad or mum().discover(".star-link").removeClass("crammed");
    $(starIcon).dad or mum().discover(".star-link:lt(" + (score) + ")").addClass("crammed"); 
    submitRating(answerId, score);
}

perform submitRating(answerId, score) {
    $.ajax({
        url: 'save_rating.php',
        kind: 'POST',
        knowledge: { 'score': score, 'answerId': answerId}
    });
}

$(doc).prepared(perform() {
    $(".star-link").on("mouseover", perform() {
        var index = $(this).index();
        $(this).dad or mum().discover(".star-link").every(perform(loopIndex) {
            if(loopIndex <= index) {
                $(this).removeClass("hout");
                $(this).addClass("hovered");
            }
            if(loopIndex > index) {
                $(this).removeClass("hovered");
                $(this).addClass("hout");
            }
        });
    });

    $(".rating-container").on("mouseout", perform() {
        $(".star-link").removeClass("hout");
        $(".star-link").removeClass("hovered");
    });
});

5. Insert or replace HTML star score on choose

On clicking the star icons beneath the solutions, the added score saved to the database utilizing a server-side code.

This code checks if the present person already rated the actual article. If that’s the case, it’ll replace solely the star_count. In any other case, it’ll insert a brand new row on to the tbl_answer_rating desk.

save_rating.php

<?php
session_start();
require_once __DIR__ . '/lib/QAModel.php';

$QAModel = new QAModel();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rating']) && isset($_POST['answerId'])) {
    $score = $_POST['rating'];
    $answerId = $_POST['answerId'];
    $userId = 3;
    $isStarRated = $QAModel->getUserRating($answerId, $userId);
    if(empty($isStarRated)) {
        $QAModel->insertRating($answerId, $userId, $score);
    } else {
        $QAModel->updateRating($score, $isStarRated[0]["id"]);
    }
}
exit;
?>

Database queries with a mannequin class

The beneath mannequin class prepares question so as to add or replace star score within the database. It shops person’s score within the DB desk to retrieve and present it within the view.

lib/QAModel.php

<?php
class QAModel
{
    personal $conn;

    perform __construct()
    {
        require_once 'DataSource.php';
        $this->conn = new DataSource();
    }

    perform getQuestion()
    {
        $sqlSelect = "SELECT * FROM tbl_question";
        $consequence = $this->conn->choose($sqlSelect);
        return $consequence;
    }

    perform getAnswer()
    {
        $sql = "SELECT  a.*, AVG(ar.star_count) AS average_star_count FROM tbl_answer a LEFT JOIN tbl_answer_rating ar ON a.id = ar.ans_id GROUP BY  a.id, a.reply ORDER BY a.id DESC";
        
        $consequence = $this->conn->choose($sql);
        return $consequence;
    }


    perform insertAnswer($reply, $user_id, $question_id)
    {
        $sql = "INSERT INTO tbl_answer (reply, user_id, question_id) VALUES (?,?,?)";
        $paramType = "sii";
        $paramArray = array($reply, $user_id, $question_id);
        $consequence = $this->conn->insert($sql, $paramType, $paramArray);
        return $consequence;
    }

    perform insertRating($answerId, $userId, $score)
    {
        $sql = "INSERT INTO tbl_answer_rating (ans_id, user_id, star_count) VALUES (?, ?, ?)";
        $paramType = "iii";
        $paramArray = array($answerId, $userId, $score);
        $consequence = $this->conn->insert($sql, $paramType, $paramArray);

        if ($consequence === false) {
            return;
        }
        return true;
    }

    perform updateRating($score, $ratingId)
    {
        $sql = "UPDATE tbl_answer_rating SET star_count = ? WHERE id = ?";
        $paramType = "ii";
        $paramArray = array($score, $ratingId);
        $consequence = $this->conn->execute($sql, $paramType, $paramArray);

        if ($consequence === false) {
            return;
        }
        return true;
    }

    perform getUserRating($answerId, $userId)
    {
        $sql = "SELECT * FROM tbl_answer_rating WHERE ans_id = ? AND user_id = ?";
        $paramType = "ii";
        $paramArray = array($answerId, $userId);
        $consequence = $this->conn->choose($sql, $paramType, $paramArray);

        return $consequence;
    }
}
?>

Database SQL script

The database script comprises the desk construction with some preliminary knowledge for the query and solutions.

sql/database.sql

--
-- Database: `db_question_answer_rating`
--

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

--
-- Desk construction for desk `tbl_answer`
--

CREATE TABLE `tbl_answer` (
  `id` int(11) NOT NULL,
  `reply` varchar(255) NOT NULL,
  `user_id` int(11) NOT NULL,
  `question_id` int(11) NOT NULL,
  `answered_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `star_count` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping knowledge for desk `tbl_answer`
--

INSERT INTO `tbl_answer` (`id`, `reply`, `user_id`, `question_id`, `answered_at`, `star_count`) VALUES
(1, 'It's a idea of attributing steel states about needs, beliefs, feelings and all.', 2, 1, '2024-03-23 10:06:29', NULL),
(2, 'It's a idea of predicting the behaviour. And, it's a research of researching the similarities and differnces.', 2, 1, '2024-03-23 10:06:47', NULL);

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

--
-- Desk construction for desk `tbl_answer_rating`
--

CREATE TABLE `tbl_answer_rating` (
  `id` int(11) NOT NULL,
  `ans_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `star_count` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

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

--
-- Desk construction for desk `tbl_question`
--

CREATE TABLE `tbl_question` (
  `id` int(11) NOT NULL,
  `query` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping knowledge for desk `tbl_question`
--

INSERT INTO `tbl_question` (`id`, `query`) VALUES
(1, 'What's 'principle of thoughts' within the context of understanding the intelligence of apes and human?');

--
-- Indexes for dumped tables
--

--
-- Indexes for desk `tbl_answer`
--
ALTER TABLE `tbl_answer`
  ADD PRIMARY KEY (`id`),
  ADD KEY `fk_question_id` (`question_id`) USING BTREE;

--
-- Indexes for desk `tbl_answer_rating`
--
ALTER TABLE `tbl_answer_rating`
  ADD PRIMARY KEY (`id`),
  ADD KEY `fk_ans_id` (`ans_id`) USING BTREE;

--
-- Indexes for desk `tbl_question`
--
ALTER TABLE `tbl_question`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for desk `tbl_answer`
--
ALTER TABLE `tbl_answer`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT for desk `tbl_answer_rating`
--
ALTER TABLE `tbl_answer_rating`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for desk `tbl_question`
--
ALTER TABLE `tbl_question`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- Constraints for dumped tables
--

--
-- Constraints for desk `tbl_answer`
--
ALTER TABLE `tbl_answer`
  ADD CONSTRAINT `tbl_answer_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `tbl_question` (`id`) ON DELETE CASCADE;

--
-- Constraints for desk `tbl_answer_rating`
--
ALTER TABLE `tbl_answer_rating`
  ADD CONSTRAINT `tbl_answer_rating_ibfk_1` FOREIGN KEY (`ans_id`) REFERENCES `tbl_answer` (`id`) ON DELETE CASCADE;

View demo Obtain

Vincy
Written by Vincy, an online developer with 15+ years of expertise and a Masters diploma in Pc Science. She makes a speciality of constructing trendy, light-weight web sites utilizing PHP, JavaScript, React, and associated applied sciences. Phppot helps you in mastering net improvement via over a decade of publishing high quality tutorials.

↑ Again to High

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments