What are the best practices for inserting data into a table in PHP when certain conditions need to be met, such as checking for existing entries before insertion?

When inserting data into a table in PHP and needing to check for existing entries before insertion, it is best practice to first query the database to see if the data already exists. If it does not exist, then proceed with the insertion. This can be achieved by using a SELECT query to check for existing entries based on certain conditions, and then conditionally executing an INSERT query if no matching entries are found.

// Assume $conn is the database connection object

// Data to be inserted
$data = [
    'column1' => 'value1',
    'column2' => 'value2',
    // Add more columns and values as needed
];

// Check if data already exists
$stmt = $conn->prepare("SELECT * FROM your_table WHERE column1 = :value1 AND column2 = :value2");
$stmt->execute([
    'value1' => $data['column1'],
    'value2' => $data['column2']
]);

if($stmt->rowCount() == 0) {
    // Data does not exist, proceed with insertion
    $insertStmt = $conn->prepare("INSERT INTO your_table (column1, column2) VALUES (:value1, :value2)");
    $insertStmt->execute([
        'value1' => $data['column1'],
        'value2' => $data['column2']
    ]);
    echo "Data inserted successfully";
} else {
    echo "Data already exists";
}