How can PHP be used to automate the process of importing CSV data into a MySQL database?
To automate the process of importing CSV data into a MySQL database using PHP, you can write a script that reads the CSV file, parses its data, and inserts it into the MySQL database using SQL queries. This can be achieved by using PHP's built-in functions for file handling and MySQL database connectivity.
<?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 connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read the CSV file
$csvFile = 'data.csv';
$file = fopen($csvFile, 'r');
// Parse and insert data into the MySQL database
while (($data = fgetcsv($file)) !== FALSE) {
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('" . $data[0] . "', '" . $data[1] . "', '" . $data[2] . "')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close the file and database connection
fclose($file);
$conn->close();
?>
Keywords
Related Questions
- What are the potential pitfalls of executing PHP functions through JavaScript onclick events in HTML?
- Are there any common pitfalls or issues to be aware of when using sessions in PHP for login forms?
- How can PHP developers ensure that htmlentities() is applied only to specific sections of a string, while excluding certain parts enclosed by specific delimiters?