How can the issue of SQL injection be addressed when preparing statements in PHP for database queries?
SQL injection can be addressed by using prepared statements in PHP when preparing database queries. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed. This method binds parameters to the SQL query, ensuring that user input is treated as data rather than executable code.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();