Php MySQL中动态表选择的替代方案

Php MySQL中动态表选择的替代方案,php,sql,mysqli,Php,Sql,Mysqli,有人告诉我,在MySQL查询中动态选择一个表是一种不好的做法,除了将所有内容都放在一个表中之外,我找不到替代当前代码的方法。如果这没有意义,也许我现在的代码会更有意义 $where = $_GET['section']; $mysqli = mysqli_connect("localhost", "root", "", "test"); if ($stmt = mysqli_prepare($mysqli, "SELECT title, img, active, price FROM ? OR

有人告诉我,在MySQL查询中动态选择一个表是一种不好的做法,除了将所有内容都放在一个表中之外,我找不到替代当前代码的方法。如果这没有意义,也许我现在的代码会更有意义

$where = $_GET['section'];
$mysqli = mysqli_connect("localhost", "root", "", "test");

if ($stmt = mysqli_prepare($mysqli, "SELECT title, img, active, price FROM ? ORDER by ID limit 5 ")) {
    mysqli_stmt_bind_param($stmt, 's', $where);

    while ($row = mysqli_fetch_assoc($stmt)) {
        if ($row['active'] == "yes") {
            echo'
我现在知道不能使用预先准备好的语句来选择表,但我现在不确定如何处理这个问题

我想:

$where = $_GET['section'];
$mysqli = mysqli_connect("localhost", "root", "", "test");
if ($where == "sets") {
    $query = "SELECT title, img, active, price FROM sets;"
}

if ($stmt = mysqli_prepare($mysqli, $query)) {
    while ($row = mysqli_fetch_assoc($stmt)) {
        if ($row['active'] == "yes") {
            echo'do stuff here';
        }

但我相信这也是一种坏习惯。对于我应该向哪个方向提出的任何建议,我都表示感谢,我为这篇冗长的文章道歉。

如果您使用可接受值的白名单验证表名的有效性,您可以动态选择表名。正如您所发现的那样,由于不能将准备好的语句占位符用作表名,因此这是最安全的替代方法

// Build an array of table names you will permit in this query
$valid_tables = array('sets', 'othertable', 'othertable2');

// Verfiy that $_GET['section'] is one of your permitted table strings
// by using in_array()
if (in_array($_GET['section'], $valid_tables)) {
  // Build and execute your query
  $where = $_GET['section']
  $query = "SELECT title, img, active, price FROM $where;";
  // etc...
}
else {
  // Invalid table name submitted.  Don't query!!!
}

如果使用可接受值的白名单验证表名的有效性,则可以动态选择表名。正如您所发现的那样,由于不能将准备好的语句占位符用作表名,因此这是最安全的替代方法

// Build an array of table names you will permit in this query
$valid_tables = array('sets', 'othertable', 'othertable2');

// Verfiy that $_GET['section'] is one of your permitted table strings
// by using in_array()
if (in_array($_GET['section'], $valid_tables)) {
  // Build and execute your query
  $where = $_GET['section']
  $query = "SELECT title, img, active, price FROM $where;";
  // etc...
}
else {
  // Invalid table name submitted.  Don't query!!!
}

您是否有几个结构相同(或非常相似)的表?有没有充分的理由不将它们合并为一个表?@Okonomiyaki这些表是相似的,只是我希望url中的get变量能够输出不同的产品。我可以把它们放在一个表中,但是有很多产品。也许,你可以把所有这些产品放在一个表中,添加一个“section”列,然后在该列上添加一个索引。实际上,您有多少百万种产品?是因为您有几个具有相同(或非常相似)结构的表吗?有没有充分的理由不将它们合并为一个表?@Okonomiyaki这些表是相似的,只是我希望url中的get变量能够输出不同的产品。我可以把它们放在一个表中,但是有很多产品。也许,你可以把所有这些产品放在一个表中,添加一个“section”列,然后在该列上添加一个索引。实际上,您有多少百万种产品?除了硬编码的白名单之外,请先运行并捕获一个
SHOW TABLES
查询,以获取数据库中要用作白名单的实时表列表:。当然,您可能仍然需要在编程上对允许客户端操作的表进行挑剔。除了硬编码的白名单,还可以先运行并捕获
SHOW tables
查询,以获取数据库中要用作白名单的表的实时列表:。当然,您可能仍然需要在编程上对允许客户机操作的表进行挑剔。