What is the purpose of using PHP to import a CSV file into MySQL?
When importing a CSV file into MySQL using PHP, the purpose is to easily transfer large amounts of data from a CSV file into a MySQL database. This process can be automated and streamlined using PHP scripts, allowing for efficient data migration and manipulation.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Path to the CSV file
$csv_file = 'path/to/csv/file.csv';
// Open the CSV file
if (($handle = fopen($csv_file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('" . $data[0] . "', '" . $data[1] . "', '" . $data[2] . "')";
$conn->query($sql);
}
fclose($handle);
}
$conn->close();
?>
Keywords
Related Questions
- What are the potential pitfalls of trying to change language labels on a webpage using PHP without incorporating JavaScript or AJAX?
- What are some common mistakes to avoid when trying to populate a dropdown field with database entries in PHP?
- What potential issues or errors could arise from using date("0") incorrectly?