How can data from CSV files be securely and efficiently transferred to MySQL tables in PHP?
To securely and efficiently transfer data from CSV files to MySQL tables in PHP, you can use the PHP functions such as fopen() to read the CSV file, fgetcsv() to parse the CSV data, and mysqli functions to insert the data into the MySQL table.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Open and read the CSV file
$csvFile = fopen('data.csv', 'r');
while (($data = fgetcsv($csvFile)) !== false) {
// Insert data into MySQL table
$mysqli->query("INSERT INTO table_name (column1, column2, column3) VALUES ('$data[0]', '$data[1]', '$data[2]')");
}
// Close the CSV file
fclose($csvFile);
// Close MySQL connection
$mysqli->close();
?>
Keywords
Related Questions
- How can the use of htmlspecialchars function enhance the security of PHP forms and prevent XSS attacks?
- How can PHP developers prevent users from manipulating form data to change prices before submission?
- What are some best practices for handling error messages in PHP scripts, especially when dealing with database queries?