How can PHP scripts be optimized to prevent duplicate entries in a database when importing data from external sources like XML?
To prevent duplicate entries in a database when importing data from external sources like XML, you can check if the entry already exists in the database before inserting it. This can be done by querying the database with the unique identifier of the entry (such as an ID or a combination of fields) and only inserting the data if no matching entry is found.
// Assume $xmlData contains the data from the XML file
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Parse the XML data
$xml = simplexml_load_string($xmlData);
// Check if the entry already exists in the database
$stmt = $pdo->prepare("SELECT * FROM table WHERE unique_id = :unique_id");
$stmt->bindParam(':unique_id', $xml->unique_id);
$stmt->execute();
$result = $stmt->fetch();
// Insert the data if no matching entry is found
if (!$result) {
$stmt = $pdo->prepare("INSERT INTO table (unique_id, data1, data2) VALUES (:unique_id, :data1, :data2)");
$stmt->bindParam(':unique_id', $xml->unique_id);
$stmt->bindParam(':data1', $xml->data1);
$stmt->bindParam(':data2', $xml->data2);
$stmt->execute();
}