What are the best practices for constructing SQL queries with dynamic input in PHP?

When constructing SQL queries with dynamic input in PHP, it is crucial to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL code from user input, ensuring that input is treated as data rather than executable code. This approach also helps improve performance by allowing the database to optimize query execution.

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

// Prepare a SQL statement with a placeholder for dynamic input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the dynamic input to the placeholder
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

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

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

// Process the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}