How does using INSERT IGNORE and checking affected rows compare to using a separate SELECT statement for error handling in PHP?

When inserting data into a database using INSERT IGNORE, the affected rows can be checked to determine if the insertion was successful. This method allows for error handling without the need for a separate SELECT statement. By checking the affected rows, you can easily determine if the insertion was successful or if there was a duplicate key violation.

// Connect to database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare data for insertion
$data = [
    'name' => 'John Doe',
    'email' => 'johndoe@example.com'
];

// Insert data into database with INSERT IGNORE
$result = $mysqli->query("INSERT IGNORE INTO users (name, email) VALUES ('{$data['name']}', '{$data['email']}')");

// Check if insertion was successful
if ($mysqli->affected_rows > 0) {
    echo "Data inserted successfully!";
} else {
    echo "Error inserting data: " . $mysqli->error;
}

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