What are the potential pitfalls of using the "IF NOT EXISTS" condition in MySQL queries when inserting data based on specific criteria?

Using the "IF NOT EXISTS" condition in MySQL queries when inserting data based on specific criteria can lead to potential race conditions. To solve this issue, you can use a unique index in the database table to prevent duplicate entries.

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

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Define the query with a unique index constraint
$query = "INSERT IGNORE INTO table_name (column1, column2) VALUES ('value1', 'value2')";

// Execute the query
if ($connection->query($query) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $query . "<br>" . $connection->error;
}

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