What are some methods to prevent spamming when form data is being submitted to a database in PHP?

Spamming when form data is being submitted to a database in PHP can be prevented by implementing CAPTCHA verification, using honeypot fields, and setting form submission limits. CAPTCHA verification requires users to complete a challenge to prove they are human, while honeypot fields are hidden form fields that should not be filled out by legitimate users. Setting submission limits can prevent multiple submissions from the same IP address within a short period of time.

// Check if CAPTCHA verification is successful
if($_POST['captcha'] != $_SESSION['captcha']){
    // CAPTCHA verification failed, handle error
}

// Check if honeypot field is empty
if(!empty($_POST['honeypot'])){
    // Honeypot field filled, likely spam, handle error
}

// Check submission limit by IP address
$ip = $_SERVER['REMOTE_ADDR'];
$limit = 3; // Limit to 3 submissions per IP
$query = "SELECT COUNT(*) as count FROM submissions WHERE ip_address = '$ip' AND submission_time > DATE_SUB(NOW(), INTERVAL 1 HOUR)";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);

if($row['count'] >= $limit){
    // Submission limit reached, handle error
}