What are the best practices for dynamically generating queries with table names in PHP to avoid SQL syntax errors?

When dynamically generating queries with table names in PHP, it is important to properly sanitize and escape the table names to avoid SQL syntax errors and potential SQL injection attacks. One way to achieve this is by using prepared statements with placeholders for the table names, and then binding the table names as parameters before executing the query.

<?php
// Assuming $tableName is the dynamically generated table name
$tableName = 'users'; // Example table name

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

// Prepare the SQL query with a placeholder for the table name
$stmt = $pdo->prepare("SELECT * FROM $tableName WHERE id = :id");

// Bind the table name parameter
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

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

// Output the results
print_r($results);
?>