How can PHP be used to read data from a CSV file and store it in a MySQL database?
To read data from a CSV file and store it in a MySQL database using PHP, you can use the fgetcsv function to read each line of the CSV file, parse it into an array, and then insert that data into the MySQL database using SQL queries.
<?php
// Connect to MySQL database
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');
// Loop through each line of the CSV file
while (($data = fgetcsv($csvFile)) !== false) {
// Insert data into MySQL database
$mysqli->query("INSERT INTO table_name (column1, column2, column3) VALUES ('" . $data[0] . "', '" . $data[1] . "', '" . $data[2] . "')");
}
// Close the CSV file
fclose($csvFile);
// Close the MySQL connection
$mysqli->close();
?>
Keywords
Related Questions
- What is the significance of using $_GET and $_POST in PHP scripts, especially in the context of PHP 5?
- In the provided code snippet, what are some potential pitfalls that could lead to a parsing error in PHP?
- How can PHP developers streamline the process of querying and inserting data into multiple tables in a database to ensure data integrity and avoid duplication?