What is the best way to import a locally stored CSV file into MySQL using PHP?
To import a locally stored CSV file into MySQL using PHP, you can use the LOAD DATA INFILE SQL statement. This statement allows you to load data from a CSV file directly into a MySQL table. You will need to establish a database connection, specify the file path of the CSV file, and define the table structure where the data will be imported.
<?php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Specify file path of CSV file
$csv_file = 'path/to/your/file.csv';
// Define table structure for data import
$sql = "LOAD DATA INFILE '$csv_file'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS";
// Execute SQL statement
if ($conn->query($sql) === TRUE) {
echo "CSV file imported successfully.";
} else {
echo "Error: " . $conn->error;
}
// Close database connection
$conn->close();
?>