What are the potential pitfalls of using a select statement to check for existing records before inserting in PHP?

One potential pitfall of using a select statement to check for existing records before inserting in PHP is the possibility of race conditions, where another process inserts a record between the select and insert statements. To solve this issue, you can use a unique constraint or index on the column(s) that should be unique to prevent duplicate records.

// Check if record already exists before inserting
$existingRecord = $pdo->query("SELECT * FROM your_table WHERE unique_column = :value")->fetch();

if(!$existingRecord){
    // Insert new record
    $stmt = $pdo->prepare("INSERT INTO your_table (unique_column, other_column) VALUES (:value, :other_value)");
    $stmt->execute(['value' => $value, 'other_value' => $otherValue]);
    echo "Record inserted successfully";
} else {
    echo "Record already exists";
}