How can PHP be used to prevent accidentally creating duplicate customer entries in a MySQL database?

To prevent accidentally creating duplicate customer entries in a MySQL database, we can use PHP to first check if a customer with the same details already exists before inserting a new entry. This can be done by querying the database to search for a matching customer based on unique identifiers such as email address or phone number. If a matching customer is found, we can display an error message to the user and prevent the duplicate entry from being added.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if customer already exists
$email = $_POST['email'];
$phone = $_POST['phone'];

$query = "SELECT * FROM customers WHERE email = '$email' OR phone = '$phone'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    echo "Customer already exists!";
} else {
    // Insert new customer entry
    $name = $_POST['name'];
    $address = $_POST['address'];
    
    $insert_query = "INSERT INTO customers (name, email, phone, address) VALUES ('$name', '$email', '$phone', '$address')";
    mysqli_query($connection, $insert_query);
    
    echo "Customer entry added successfully!";
}

// Close database connection
mysqli_close($connection);