What are the potential pitfalls of using variables like $table in SQL queries in PHP?

Using variables like $table in SQL queries in PHP can potentially lead to SQL injection attacks if the variable is not properly sanitized. To prevent this, it's important to use prepared statements with parameterized queries instead of directly concatenating variables into the SQL query string.

// Example of using prepared statements to prevent SQL injection

// Assuming $table is the variable holding the table name
$table = 'users';

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

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

// Bind the parameter value to the placeholder
$stmt->bindParam(':id', $id);

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

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