Home > Enterprise >  How can I dynamically generate a table name in a SQL query?
How can I dynamically generate a table name in a SQL query?

Time:12-29

I have a SQL Query that uses MySQL database to get information from. The table names are first constant with a different IMEI number as it's end.

gs_object_data_12345678

The 12345678 is identified as $_GET in my script but when I try change table name it does not show the data in that table

$imei = $_GET['imei'];

 $result = $db->query("SELECT * FROM gs_object_data_'$imei' LIMIT 200 ");

If I use the string as below it works

$result = $db->query("SELECT * FROM gs_object_data_12345678 LIMIT 200 ");

I need to change the table name with the $_GET information

The URL alarm_action.php?id=58543&reg=****&imei=862202228007105 has IMEI in it so the information should pull thru

CodePudding user response:

For me, this code works fine. My only advice is to validate your incoming data well.

$imei = $_GET['imei'];
$table_name = "gs_object_data_".$imei;
$query="SELECT * FROM $table_name LIMIT 200";
$result = $db->query($query);

Depending on your MySQL settings, you could add back quotes.

$query="SELECT * FROM `$table_name` LIMIT 200";

CodePudding user response:

use like below

$imei = $_GET['imei'];
$result = $db->query("SELECT * FROM `gs_object_data_".$imei."` LIMIT 200 ");

CodePudding user response:

use like this

$imei = $_GET['imei'];
$result = $db->query("SELECT * FROM gs_object_data_" . $imei . " LIMIT 200 ");

or

$result = $db->query("SELECT * FROM gs_object_data_{$imei} LIMIT 200 ");

Be Aware How does the SQL injection from the "Bobby Tables" XKCD comic work?


In protected way

$imei = $_GET['imei'];

$stmt = $db->prepare("SELECT * FROM gs_object_data_? LIMIT 200");
$stmt->bind_param("s", $imei);
$stmt->execute();

$result = $stmt->get_result();
  • Related