How can PHP be used to insert data from a CSV file into a database?
To insert data from a CSV file into a database using PHP, you can read the CSV file line by line, parse each line to get the data, and then insert it into the database using SQL queries. This can be done using PHP functions like fopen(), fgetcsv(), and mysqli_query().
<?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);
}
// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');
// Loop through each line in the CSV file
while (($data = fgetcsv($csvFile)) !== FALSE) {
// Insert data into the database
$sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('" . $data[0] . "', '" . $data[1] . "', '" . $data[2] . "')";
$conn->query($sql);
}
// Close the CSV file
fclose($csvFile);
// Close the database connection
$conn->close();
?>
Keywords
Related Questions
- How can PHP be used to automatically populate a table with user information from a registration form, while excluding passwords?
- How can including files in PHP be optimized to avoid errors like the one mentioned in the forum thread?
- Are there any best practices for handling email validation in PHP registration forms?