Using a variable for table name in PDO

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

The above works fine.

I have a variable for the table name “myTable1” like the following.

$tableName = 'myTable1';

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

The code above produces the result below.

How can I use a variable for the table name without the Fatal error above ?

Try echoing the SELECT string and see what is displayed.

Also I prefer this syntax:

$sql = 'SELECT title FROM $tableName WHERE id = ?' ;

$myQuery=$dbc-> prepare ( $sql );

Where is the value for $tableName coming from?

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)


100% rpkamp.

As a side note, be very careful about what you do with variable table names.

PDO’s prepared queries are designed so that you DONT put variables directly into the queries for good reason.

If I manage to get $tableName to equal “mysql.user; DELETE * FROM anytable”, your website is suddenly deleting itself…

1 Like

In my Post #2 I was hoping the OP would echo the string and spot the mistake. I think it’s a far better way of learning rather than be given a solution to cut and paste.



If it is hard coded, like your example:-

…it may well be OK.

But something like:-

$tableName = $_GET['table'] ;

…or similar should definitely be avoided at all cost.
But there are less obvious ways that could also be a risk.