I want to execute one and the same sql statement for a series of tables e.g. 37 tables.
For the table object name of each queried table I want to use a php variable named '$table'. The object names of the tables are provided in an included php file 'tables.php'.
The variable '$table' is generated repetitively from a concatenation of the string '$table' and an array '$numbers' for each table number, and put into the statement.
SQL reads the generated variable e.g. '$table1'. But I get an error from SQL Server for the FROM clause:
[SQL Server]Incorrect syntax near '$table1'.
I put the variable '$table' in brackets and quotation marks but it did not help.
Please help!
//php script one, 'tables.php':
$table1 = 'myTable1';
$table2 = 'myTable2';
...
$table37 = 'myTable37';
//php script two:
include_once('tables.php');
$numbers = range(1,37);
foreach($numbers as $number) {
$table = '$table' . $number;
$stmt = $db_conn->prepare("SELECT * FROM $table;");
$stmt->execute();
}
This is the solution provided by Hasan. The magic is to put the concat for variable '$table' in curly brackets led by $:
include_once('tables.php'); //provides table object names for variables $table1, $table2, etc., e.g. $table1 = 'mytable1_in_database';
//first number of a closed range of variables for tables to be queried
$i = 1;
//last number of closed range of variables for tables to be queried
$j = 37;
for($i=1; $i<=$j; $i++) {
$table = ${'table' . $i};
$stmt = $db_conn->prepare("SELECT * FROM $table;");
$stmt->execute();
}