1

我试图根据用户选择的选项值中的任何或所有选择来创建动态查询。例如,如果他们选择项目 ID,则查询将返回项目 ID、规模和存储在第二个表中的课程,或者如果他们选择了规模和部门,则将执行另一个查询。显示所有选定大小的项目以及针对它的课程。

这是我到目前为止所得到的。我真的可以得到一些帮助。

<?php 
$pid = $_POST['project_id'] ;
$psize = $_POST['projectSize'] ;
$pdepts = $_POST['depts'] ;
$lstage = $_POST['stage'] ;
$ltype = $_POST['type'] ;
$impacted = $_POST['impacted'] ;


$sqlString = null;
echo "Total Number Of Captured Post Variables is:";
echo count($_POST);

echo '<br />';

 $number = 0;

foreach ($_POST as $param_name => $param_val ) {

if ($param_val ==""){


   }else{

     $number++;

   }

echo "Param: $param_name = $param_val<br />\n";
}
if($number ==1) {

}else{

}

?>
4

3 回答 3

2

我希望这可以帮助一点,我还添加了数组检查,你需要检查安全性和注入:)

<?php 
$pid = $_POST['project_id'] ;
$psize = $_POST['projectSize'] ;
$pdepts = $_POST['depts'] ;
$lstage = $_POST['stage'] ;
$ltype = $_POST['type'] ;
$impacted = $_POST['impacted'] ;
//Your columns in the DB 
$columns = array('project_id'=>'project_id','project_size'=>'project_size','depts'=>'depts','stage'=>'stage'); 

$sqlString = null;
echo "Total Number Of Captured Post Variables is:";
echo count($_POST);

echo '<br />';

 $number = 0;
$queryStr = ""; 
$preStr = array(); 
foreach ($_POST as $key => $val ) {

if (!empty($_POST[$key])){
       if(!is_array($_POST[$key]))
           $currentStr = $columns[$key]." = ".$val; 
       else
           $currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")"; 

       $preStr[] = $currentStr; 
   }
 }

$queryStr = "SELECT * FROM tableName WHERE ".implode(' AND ',$preStr);
echo $queryStr; 

if($number ==1) {

}else{

}

?>
于 2013-05-14T13:28:30.513 回答
0

让它工作到这样的地步:当我回显 $queryStr 时,它输出为“SELECT FROM table WHERE”等。

然后如何将该查询的输出显示到结果表中?

于 2013-05-15T07:43:01.953 回答
0

它非常简单,只需为您要运行的每个查询运行一个条件:

if(isset($_POST['project_id'])){
    //they selected a Project ID.
    //write the query will return with the project ID, size and a lesson stored in a second table
} elseif (isset($_POST['projectSize']) && isset($_POST['depts'])){
   //they selected a size and department
   // write a query displaying all projects that are of the chosen size with the lessons against it.
} elseif (some other condition ){
   //you can keep adding conditions 
}

最后,您可能希望使用mysql_real_escape_string

于 2013-05-14T13:30:26.100 回答