What are some best practices for dynamically passing variables in MySQL queries in PHP?

When dynamically passing variables in MySQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. This involves using placeholders in the query and binding the variables to those placeholders before executing the query.

// Example of dynamically passing variables in MySQL queries using prepared statements

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

// Define the query with placeholders
$sql = "SELECT * FROM users WHERE id = :id";

// Prepare the statement
$stmt = $pdo->prepare($sql);

// Bind the variable to the placeholder
$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

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

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