Using a variable for table name in PDO

Your query is using single quotes 'SELECT title FROM $tableName WHERE id = ?'.

In single quoted strings variables aren’t expanded, so the string $tableName is literally being sent to the server, it’s not replaced with the value of the $tableName variable.

If you want that you should use a double quoted string

$myQuery=$dbc-> prepare ("SELECT title FROM $tableName
WHERE id = ?");

(see that $tableName is green my example whereas it’s red in yours? A good IDE helps a lot with this kind of stuff too - like PhpStorm, or Visual Studio Code)

4 Likes