I always use PDO when making MySQL connections from PHP and it works as expected when my execution variables are parts of the WHERE
statements in the query. An example of this could be this:
$stmt = $dbh->prepare("SELECT name FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
Let's say I want to fetch a dynamic column name in the query above. I would expect the following query to work:
$stmt = $dbh->prepare("SELECT name, :dynamic_column FROM users WHERE id = :id");
$stmt->execute(['dynamic_column' => 'age', 'id' => 1]);
...but it doesn't. The only way I can add dynamic column names or table names to a query is by adding php-variables directly to the query like this:
$stmt = $dbh->prepare("SELECT name, $dynamic_column FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
... which will work. But by going with this solution, the whole point of PDO is gone.
My question is now; what is the best practice when the variable I want to add to my query is a table name or a column name?