How can PHP be used to assign a rating link to specific images in a gallery and display them on the same page after the rating is submitted?

To assign a rating link to specific images in a gallery and display them on the same page after the rating is submitted, you can use PHP to dynamically generate the rating links for each image. When a user submits a rating, you can store the rating in a database and then retrieve and display the updated ratings for each image on the same page.

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

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

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

// Retrieve images from database
$sql = "SELECT * FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Display image
        echo '<img src="' . $row["image_url"] . '" alt="' . $row["image_alt"] . '">';
        
        // Display rating link
        echo '<a href="rate.php?image_id=' . $row["image_id"] . '">Rate this image</a>';
        
        // Retrieve and display rating for image
        $rating_sql = "SELECT AVG(rating) AS average_rating FROM ratings WHERE image_id = " . $row["image_id"];
        $rating_result = $conn->query($rating_sql);
        $rating_row = $rating_result->fetch_assoc();
        
        echo 'Average Rating: ' . $rating_row["average_rating"];
    }
} else {
    echo "0 results";
}

$conn->close();
?>