What potential pitfalls should be considered when writing SQL queries in PHP for data analysis?
One potential pitfall when writing SQL queries in PHP for data analysis is SQL injection attacks. To prevent this, it is important to use prepared statements with parameterized queries to sanitize user input and prevent malicious code from being executed.
// Example of using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
// Process the data
}