How can PHP be used to increment and store ratings based on user input?

To increment and store ratings based on user input in PHP, you can create a database table to store the ratings along with the associated item. When a user submits a rating, you can retrieve the current rating from the database, increment it by the user input, and then update the database with the new rating.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "ratingsDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve current rating for item
$item_id = $_POST['item_id'];
$sql = "SELECT rating FROM ratings WHERE item_id = $item_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $current_rating = $row['rating'];
}

// Increment rating based on user input
$user_input = $_POST['user_rating'];
$new_rating = $current_rating + $user_input;

// Update database with new rating
$sql = "UPDATE ratings SET rating = $new_rating WHERE item_id = $item_id";
$conn->query($sql);

// Close connection
$conn->close();
?>