How can unnecessary code be avoided when constructing SQL queries in PHP?

Unnecessary code in SQL queries in PHP can be avoided by using prepared statements with parameterized queries. This helps prevent SQL injection attacks and ensures that only necessary code is included in the query. By binding parameters to placeholders in the query, the database engine can distinguish between code and data, improving security and efficiency.

// Example of using prepared statements to avoid unnecessary code in SQL queries
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    echo $row['username'] . "<br>";
}