What are the potential pitfalls of using arrays in SQL queries in PHP?
When using arrays in SQL queries in PHP, one potential pitfall is the risk of SQL injection attacks if the array values are not properly sanitized. To prevent this, it is important to use prepared statements with parameterized queries to safely pass array values to the SQL query.
// Example of using prepared statements with arrays in SQL queries in PHP
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
// Array of values to be inserted into the database
$usernames = ['user1', 'user2', 'user3'];
// Prepare a statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO users (username) VALUES (:username)");
// Bind the array values to the parameter and execute the query for each value
foreach ($usernames as $username) {
$stmt->bindParam(':username', $username);
$stmt->execute();
}