What are common pitfalls to avoid when executing SQL statements in PHP, especially when handling user input?
Common pitfalls to avoid when executing SQL statements in PHP, especially when handling user input, include SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to sanitize user input and avoid directly concatenating user input into SQL queries.
// Example of using prepared statements to avoid SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize user input
$user_input = $_POST['user_input'];
// Prepare a SQL statement with a parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $user_input);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();