CCCPaste

sql_PHP-INSERT-TRY-CATCH-ERRORS

<?php

// Assume $pdo is a PDO connection with ERRMODE_EXCEPTION enabled.

try {

// Prepare the INSERT
$stmt = $pdo->prepare("
INSERT INTO eng_events.`260227_ais_workshop_registration`
(full_name, email, affiliation, phone)
VALUES
(:full_name, :email, :affiliation, :phone)
");

// Bind parameters
$stmt->execute([
':full_name' => $_POST['full_name'],
':email' => $_POST['email'],
':affiliation' => $_POST['affiliation'],
':phone' => $_POST['phone']
]);

// If we reach this point, the INSERT succeeded
echo "Thank you for your submission.";

} catch (PDOException $e) {

// SQLSTATE 23000 = integrity constraint violation
if ($e->getCode() === '23000') {

// You can inspect $e->getMessage() to map specific constraints
// to specific user-friendly messages if you want.
// Example:
if (strpos($e->getMessage(), 'chk_affiliation') !== false) {
echo "Your submission was not recorded. Please choose a valid affiliation.";
exit;
}

if (strpos($e->getMessage(), 'chk_email') !== false) {
echo "Your submission was not recorded. Please enter a valid email address.";
exit;
}

// Fallback for any other constraint violation
echo "Your submission was not recorded. Please review your entries and try again.";
exit;
}

// Any other database error
echo "A system error occurred. Please try again later.";
exit;
}

?>