What are the advantages of using arrays and loops like foreach and for in PHP for processing CSV files during database imports?
When processing CSV files during database imports in PHP, using arrays and loops like foreach and for can greatly simplify the parsing and insertion of data into the database. Arrays allow you to store the CSV data in a structured format, making it easier to access and manipulate individual fields. Loops like foreach and for can then be used to iterate over the array and insert the data into the database row by row.
<?php
// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');
// Initialize an empty array to store the CSV data
$data = [];
// Read each row of the CSV file and store it in the data array
while (($row = fgetcsv($csvFile)) !== false) {
$data[] = $row;
}
// Close the CSV file
fclose($csvFile);
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Iterate over the data array and insert each row into the database
foreach ($data as $row) {
$stmt = $pdo->prepare("INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)");
$stmt->execute($row);
}
// Close the database connection
$pdo = null;
?>