How can the issue of SQL injection be addressed in PHP when querying a database?

SQL injection can be addressed in PHP by using prepared statements with parameterized queries. This method allows the database to distinguish between the actual SQL code and the user input, preventing malicious code from being executed. By binding parameters to the query, the database can safely execute the query without the risk of SQL injection.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the parameter to the query
$stmt->bindParam(':username', $_POST['username']);

// Execute the statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();