How can PHP be used to compare a CSV file with a SQL database?
To compare a CSV file with a SQL database using PHP, you can read the CSV file line by line, extract the data, and then query the SQL database to check if the data already exists. You can use PHP's built-in functions for handling CSV files and SQL queries to accomplish this task.
<?php
// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');
// Read the CSV file line by line
while (($data = fgetcsv($csvFile, 1000, ",")) !== FALSE) {
// Extract data from CSV
$csvData1 = $data[0];
$csvData2 = $data[1];
// Query SQL database to check if data exists
$sql = "SELECT * FROM table WHERE column1 = '$csvData1' AND column2 = '$csvData2'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Data already exists in the database: $csvData1, $csvData2\n";
} else {
echo "Data does not exist in the database: $csvData1, $csvData2\n";
}
}
// Close the CSV file
fclose($csvFile);
// Close the database connection
$conn->close();
?>