What are the potential pitfalls of passing complex SQL statements to PDO in PHP?
Passing complex SQL statements directly to PDO in PHP can lead to SQL injection vulnerabilities if the input is not properly sanitized. To prevent this, use prepared statements with placeholders for user input to ensure that the SQL query is executed safely.
// Example of using prepared statements with PDO to prevent SQL injection
// Connect to the database
$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
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display the results
foreach ($results as $row) {
echo $row['username'] . "<br>";
}
Related Questions
- In the provided PHP code snippet, where should the nl2br() function be applied to ensure that user-entered line breaks are displayed correctly in the output?
- How can all $_GET[] parameters be accessed in PHP without knowing their names?
- What is the significance of using the u-Modifikator in PHP when dealing with UTF-8 encoded text?