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

时间:2015-10-19 10:08:17

标签: php mysql pdo zend-framework2

我想从一个例子开始:你收到了一些包含所需字段的列表。此列表可能会有所不同,即使它为空,也请选择所有字段。此列表可以包含多个表中的字段。有没有办法生成SELECT查询这样做?

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

更新1

  • 目标只是从几个表中传递字段,而不是 控制结果来自任何一个(关于第一个答案)

1 个答案:

答案 0 :(得分: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;