How can PHP developers prevent duplicate entries in a MySQL database when inserting new data?
To prevent duplicate entries in a MySQL database when inserting new data, PHP developers can use the `INSERT IGNORE` or `INSERT ON DUPLICATE KEY UPDATE` queries. These queries allow developers to handle duplicate entry errors gracefully by either ignoring them or updating the existing record.
<?php
// Establish a connection to the MySQL database
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Prepare the SQL query with INSERT IGNORE to prevent duplicate entries
$query = "INSERT IGNORE INTO table_name (column1, column2) VALUES ('value1', 'value2')";
// Execute the query
$result = $connection->query($query);
// Check if the query was successful
if ($result) {
echo "Data inserted successfully!";
} else {
echo "Error inserting data: " . $connection->error;
}
// Close the database connection
$connection->close();
?>