What are the best practices for reading data from a CSV file and inserting it into a MySQL database using PHP?
When reading data from a CSV file and inserting it into a MySQL database using PHP, it is important to handle errors, sanitize input data to prevent SQL injection, and use prepared statements for database queries to enhance security. Additionally, it is recommended to open and close the database connection only once to improve performance.
<?php
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database_name");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Read data from the CSV file
$csvFile = fopen('data.csv', 'r');
while (($data = fgetcsv($csvFile)) !== false) {
// Sanitize input data
$data = array_map(array($mysqli, 'real_escape_string'), $data);
// Insert data into MySQL database using prepared statements
$stmt = $mysqli->prepare("INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $data[0], $data[1], $data[2]);
$stmt->execute();
}
// Close the CSV file and database connection
fclose($csvFile);
$mysqli->close();
?>
Keywords
Related Questions
- How can PHP beginners effectively differentiate between multiple POST requests in their scripts?
- What considerations should be taken into account when multiple users are accessing a PHP page and storing different data for each user?
- How can PHP code be optimized to ensure proper functionality when creating new directories based on user input?