How can integrity constraint violations be prevented when inserting data into a database using PHP?

Integrity constraint violations can be prevented when inserting data into a database using PHP by validating the data before inserting it, using transactions to ensure atomicity, and setting up proper foreign key constraints in the database schema.

// Example code snippet to prevent integrity constraint violations when inserting data into a database using PHP

// Validate the data before inserting
if($dataIsValid) {
    // Start a transaction
    $pdo->beginTransaction();

    try {
        // Insert data into the database
        $stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
        $stmt->execute([$value1, $value2]);

        // Commit the transaction
        $pdo->commit();
    } catch (PDOException $e) {
        // Rollback the transaction if an error occurs
        $pdo->rollBack();
        echo "Error: " . $e->getMessage();
    }
} else {
    echo "Invalid data";
}