How can PHP code be optimized to detect and handle duplicate customer entries more efficiently and accurately?

To optimize PHP code to detect and handle duplicate customer entries more efficiently and accurately, you can use a combination of database queries and PHP logic. First, check if a customer with the same email or unique identifier already exists in the database. If a duplicate is found, handle it accordingly by updating the existing entry or displaying an error message to the user.

// Assume $email is the email of the customer being added
// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Check if the customer already exists
$query = "SELECT * FROM customers WHERE email = '$email'";
$result = $connection->query($query);

if ($result->num_rows > 0) {
    // Duplicate customer found, handle it here (e.g., update existing entry or display error message)
    echo "Customer with this email already exists";
} else {
    // Insert the new customer into the database
    $insertQuery = "INSERT INTO customers (email) VALUES ('$email')";
    $connection->query($insertQuery);
    echo "Customer added successfully";
}

// Close the database connection
$connection->close();