How can the LOAD DATA LOCAL INFILE SQL statement be utilized to directly import CSV data into a database table without the need for PHP manipulation?
To directly import CSV data into a database table without the need for PHP manipulation, you can use the LOAD DATA LOCAL INFILE SQL statement. This statement allows you to load data from a CSV file directly into a database table. By specifying the file path and table name in the SQL statement, you can efficiently import the data without the need for additional PHP code.
<?php
$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);
}
$sql = "LOAD DATA LOCAL INFILE '/path/to/file.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS";
if ($conn->query($sql) === TRUE) {
echo "CSV data imported successfully";
} else {
echo "Error importing CSV data: " . $conn->error;
}
$conn->close();
?>
Related Questions
- Are there any common pitfalls to avoid when generating HTML pages dynamically with PHP?
- How can the use of global variables like $GLOBALS['DB'] impact the scalability and maintainability of PHP code?
- What is the purpose of using a query string in PHP functions and how can it be effectively implemented?