What function is commonly used to import data from a CSV file into a MySQL database in PHP?
To import data from a CSV file into a MySQL database in PHP, the `LOAD DATA INFILE` SQL command is commonly used. This command allows you to load data from a CSV file directly into a MySQL table. You can specify the file path, the table to insert the data into, and the columns to map the data to.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Import data from CSV file
$sql = "LOAD DATA INFILE 'path/to/file.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS"; // Skip header row
if ($conn->query($sql) === TRUE) {
echo "Data imported successfully";
} else {
echo "Error importing data: " . $conn->error;
}
$conn->close();
?>
Keywords
Related Questions
- What are the steps to enable Bonjour announcement for DLNA servers on a QNAP NAS to allow streaming to Mac devices?
- What is the logic behind displaying data in columns using PHP, especially when considering alternating rows?
- What are some recommended architectures or frameworks for handling URL paths and routing in PHP?