[英]How to search database with dynamically created query?
I would like to start from an example: you received some list with needed fields. 我想从一个例子开始:您收到了一些带有必填字段的列表。 This list may vary and even if it is empty, select all fields. 此列表可能会有所不同,即使它为空,也请选择所有字段。 This list can include fields from several tables. 该列表可以包括来自多个表的字段。 Is there any way to generate SELECT query for doing this? 有什么方法可以生成SELECT查询吗?
Probably there is a way, but it will look like parsing received list, adding appropriate table alias, and then adding modified list into select clause. 可能有一种方法,但是它看起来像解析接收到的列表,添加适当的表别名,然后将修改后的列表添加到select子句中。 Is it best way actually? 实际上这是最好的方法吗?
Update 1 更新1
You could create a query that first selects dynamically fields, depending on your criteria. 您可以创建一个查询,该查询首先根据您的条件动态选择字段。
for example lets assume you have two criteria passed to you. 例如,假设您有两个条件传递给您。 Then (after you have made sure your criteria1 and criteria2 are safe): 然后(确保标准1和标准2安全后):
$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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.