Question

How do I using a variable for the name of a table in a DBI query? I know how to use placeholders as part of the where clause, but how do I do this for the table name?

I would like to do something like this:

 my $table_name='table1';
 my $query = $dbh_cgi->prepare("select * from ?");
 $query->execute($table_name);

So far, I end up getting a MySQL syntax error because DBI adds quotes around the name, table1.

Was it helpful?

Solution

One of the limitations of placeholders is that they can't be used for table names. Instead of using a placeholder, you can use a variable. To make sure the variable's contents are safe, use quote_identifier(), for example:

my $table_name='table1'; #-- Or get this from somewhere else
my $safe_table_name =  $dbh_cgi->quote_identifier($table_name);
my $query = $dbh_cgi->prepare("select * from $safe_table_name");
$query->execute();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top