How can PHP be utilized to efficiently manage and update rating data for a website or application?
To efficiently manage and update rating data for a website or application using PHP, you can store the ratings in a database and use SQL queries to update and retrieve the data. By creating functions to handle the rating updates and calculations, you can easily manage and display the ratings on your website or application.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "ratings_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Function to update the rating for a specific item
function updateRating($item_id, $new_rating) {
global $conn;
$sql = "UPDATE ratings SET rating = $new_rating WHERE item_id = $item_id";
$conn->query($sql);
}
// Function to calculate and retrieve the average rating for a specific item
function getAverageRating($item_id) {
global $conn;
$sql = "SELECT AVG(rating) AS avg_rating FROM ratings WHERE item_id = $item_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row['avg_rating'];
} else {
return 0;
}
}