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);
}
?>
Related Questions
- How can PHP developers avoid unnecessary complexity when saving loop results for further processing?
- How can you ensure that only specific instances of a character in a string are replaced in PHP?
- What are the advantages and disadvantages of using pre-built PHP modules or classes for string manipulation tasks?