What are some best practices for reading CSV files into a database table using PHP to avoid data corruption?
When reading CSV files into a database table using PHP, it is important to handle data validation and sanitization to prevent data corruption. One way to achieve this is by using prepared statements to insert data into the database, which helps to prevent SQL injection attacks. Additionally, it is recommended to check for any potential errors during the file reading process and handle them appropriately to ensure data integrity.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Open the CSV file for reading
$handle = fopen('data.csv', 'r');
// Loop through each row in the CSV file
while (($data = fgetcsv($handle)) !== false) {
// Sanitize and validate data before inserting into the database
$stmt = $pdo->prepare("INSERT INTO table (column1, column2) VALUES (?, ?)");
$stmt->execute([$data[0], $data[1]]);
}
// Close the file handle
fclose($handle);
Keywords
Related Questions
- What potential modules or configurations in Apache could lead to PHP files being downloaded?
- How can foreach loops be utilized to improve the output of regex pattern matches in PHP?
- Are there any potential pitfalls or limitations when using classes in PHP to store multiple values of different types?