如何使用动态创建的查询来搜索数据库?

How to search database with dynamically created query?

我想从一个例子开始:您收到了一些包含所需字段的列表。此列表可能会有所不同,即使它是空的,select 所有字段。此列表可以包含来自多个 table 的字段。有什么方法可以生成 SELECT 查询吗?

可能有办法,但它看起来像是解析收到的列表,添加适当的 table 别名,然后将修改后的列表添加到 select 子句中。这实际上是最好的方法吗?

更新 1

您可以创建一个首先根据您的条件选择动态字段的查询。

例如,假设您有两个标准传递给您。然后(在你确定你的 criteria1 和 criteria2 是安全的之后):

$mySelect = '';      //placeholder so that you can add select fields
$extraTables = '';   //placeholder to put the extra tables I may need
$criteria = " WHERE 1 ";    //this will select everything
if ($criteria1>'') {
  $mySelect .= ' , t3.field3 '; 
  $extraTables = " , aDifferentTable AS t3";
  $criteria .= " AND t3.someKey = t1.someKey '";
  $criteria .= " AND field_crit1 = '" . $criteria1 . "'";
}

//and an example of connecting dynamically to an other table
if ($criteria2>'') {
  $mySelect .= ' , t2.field5 '; 
  $extraTables = " , anOtherTable AS t2";
  $criteria .= " AND t2.someKey = t1.someKey '";
  $criteria .= " AND t2.field_crit2 = '" . $criteria2 . "'";
}

//lets combine all together into one dynamically created query    
$myquery = "SELECT t1.something " . $mySelect . " FROM myTable  AS t1";   

$myquery = $myqury . $extraTables . $criteria;