How can setting a UNIQUE constraint in a database table help prevent duplicate entries when inserting data from a form in PHP?
Setting a UNIQUE constraint in a database table helps prevent duplicate entries by ensuring that a specific column (or combination of columns) can only have unique values. When inserting data from a form in PHP, if a duplicate entry is attempted to be inserted into a column with a UNIQUE constraint, an error will be thrown, preventing the duplicate entry from being added to the database.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data from form into database table with a UNIQUE constraint on 'email' column
$email = $_POST['email'];
$sql = "INSERT INTO users (email) VALUES ('$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();