What are common issues when importing .csv data into a MySQL database using PHP?
One common issue when importing .csv data into a MySQL database using PHP is handling special characters or formatting errors that may cause the import to fail. To solve this, you can use the `LOAD DATA INFILE` MySQL statement with the `FIELDS TERMINATED BY` and `LINES TERMINATED BY` options to specify the delimiter and line endings in the .csv file.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Import .csv data into MySQL database
$csvFile = 'data.csv';
$tableName = 'your_table_name';
$sql = "LOAD DATA INFILE '$csvFile'
INTO TABLE $tableName
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES";
if ($conn->query($sql) === TRUE) {
echo "Data imported successfully";
} else {
echo "Error importing data: " . $conn->error;
}
// Close MySQL connection
$conn->close();