How can PHP be used to automate the process of updating data in MySQL DB tables from CSV files on a server?
To automate the process of updating data in MySQL DB tables from CSV files on a server using PHP, you can write a script that reads the CSV file, parses the data, and updates the corresponding rows in the database table. This can be achieved by using PHP's built-in functions for file handling and MySQL database connections.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the 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, 1000, ",")) !== FALSE) {
// Update the corresponding row in the database table
$sql = "UPDATE table_name SET column1 = '" . $data[1] . "', column2 = '" . $data[2] . "' WHERE id = " . $data[0];
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
// Close the CSV file and database connection
fclose($csvFile);
$conn->close();
?>
Related questions
-
PHP database text retrieval
-
PHP object instantiation method calls
-
MySQL PHP SQL injection