What potential pitfalls should be considered when writing SQL statements in PHP for database operations?
Potential pitfalls when writing SQL statements in PHP for database operations include SQL injection attacks, which can occur when user input is not properly sanitized, leading to malicious SQL code being executed. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.
// Example of using prepared statements to prevent SQL injection
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();