What is the best approach to update a SQL database table with data from a CSV file using PHP?
To update a SQL database table with data from a CSV file using PHP, you can read the CSV file line by line, parse the data, and then execute an UPDATE query for each row to update the corresponding records in the database table.
<?php
// Connect to the 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');
// Loop through each row in the CSV file
while (($data = fgetcsv($csvFile)) !== FALSE) {
$column1 = $data[0]; // Assuming the first column in the CSV file corresponds to the primary key in the database table
$column2 = $data[1]; // Assuming the second column in the CSV file corresponds to the column to be updated in the database table
// Update the database table with data from the CSV file
$sql = "UPDATE table_name SET column2 = '$column2' WHERE column1 = '$column1'";
$conn->query($sql);
}
// Close the CSV file
fclose($csvFile);
// Close the database connection
$conn->close();
?>
Keywords
Related Questions
- What are the best practices for handling form submissions and accessing HTML values in PHP?
- How can the principles of Object-Oriented Analysis and Design be applied to refactor PHP code for better maintainability and scalability in the future?
- What are common pitfalls when using while loops in PHP for data retrieval?