替代mysql中的动态表选择

时间:2012-05-25 01:59:08

标签: php sql web mysqli

我被告知,动态选择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';
                                     }

但我确信这也是不好的做法。任何指示我应该采取的方式,我很感激,我为长篇大论道歉。

1 个答案:

答案 0 :(得分:4)

您可以动态选择表名,如果您使用可接受值的白名单验证其有效性。正如您所发现的那样,您不能使用预先准备好的语句占位符来表名,这是最安全的选择。

// 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!!!
}