What are some common solutions to resolving duplicate entries in a SQL database when using PHP to insert data from a foreach loop?
When inserting data from a foreach loop into a SQL database using PHP, duplicate entries can occur if the loop iterates over the same data multiple times. One common solution to this issue is to use the REPLACE INTO or INSERT IGNORE SQL statement to handle duplicate entries. This will either update the existing row with new data or ignore the insertion if a duplicate entry is detected.
// Assuming $data is an array of data to be inserted into the database
foreach($data as $row) {
$sql = "REPLACE INTO table_name (column1, column2) VALUES ('" . $row['value1'] . "', '" . $row['value2'] . "')";
// Or use INSERT IGNORE for ignoring duplicates
// $sql = "INSERT IGNORE INTO table_name (column1, column2) VALUES ('" . $row['value1'] . "', '" . $row['value2'] . "')";
// Execute the SQL query
$result = mysqli_query($connection, $sql);
if(!$result) {
echo "Error: " . mysqli_error($connection);
}
}