What are some potential pitfalls when working with CSV files in PHP and importing them into a database?
One potential pitfall when working with CSV files in PHP and importing them into a database is handling data validation and sanitization. It's important to ensure that the data being imported is clean and formatted correctly to prevent SQL injection attacks or data corruption in the database. One way to solve this issue is by using prepared statements and parameterized queries to securely insert the data into the database.
// Example code snippet using prepared statements to import CSV data into a database
// Assuming $csvData contains the CSV data
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare the insert statement
$stmt = $pdo->prepare("INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)");
// Loop through the CSV data and insert each row into the database
foreach ($csvData as $row) {
$stmt->execute([$row[0], $row[1], $row[2]]);
}