How can prepared statements be utilized in PHP to prevent SQL injection vulnerabilities when inserting data from a CSV file into a MySQL database?

To prevent SQL injection vulnerabilities when inserting data from a CSV file into a MySQL database in PHP, prepared statements should be used. Prepared statements separate SQL logic from user input, allowing the database to distinguish between code and data. This helps prevent malicious SQL injection attacks by treating input as data rather than executable code.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

$csvFile = 'data.csv';
$handle = fopen($csvFile, "r");

if ($handle !== FALSE) {
    $stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $stmt->execute($data);
    }

    fclose($handle);
}
?>