How can you ensure that a specific ID is not inserted more than 5 times in a table using PHP?

To ensure that a specific ID is not inserted more than 5 times in a table using PHP, you can first query the database to count the number of existing records with that ID. If the count is less than 5, you can proceed with the insert operation. Otherwise, you can prevent the insertion and display an error message.

<?php

// Assuming $conn is your database connection

$id = 123; // Specify the ID you want to limit
$maxAllowed = 5; // Maximum allowed occurrences of the ID

$stmt = $conn->prepare("SELECT COUNT(*) as count FROM your_table WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if ($row['count'] < $maxAllowed) {
    // Proceed with the insert operation
} else {
    echo "Error: Maximum limit reached for ID $id";
}

$stmt->close();
$conn->close();

?>