从下拉列表中的php和sql查询

时间:2014-04-03 18:25:57

标签: php mysql

我在PHP中有6个下拉列表。用户可以选择一个下拉列表或全部,并根据用户选择我需要运行一个mysql查询。我的问题是,如果我使用AND,用户必须从所有drop中选择一个选项。如果我使用OR,结果非常奇怪。我需要一个组合值选择的解决方案,当我点击一个表格打开一个结果链接时。我现在有这个:

        <select name="categorie" class="form-control m-bot15"> 
        <option value= option 1> Option 1 </option> 
        <option value= option 2> Option 2 </option>
    </select>

    <select name="employeename" class="form-control m-bot15"> 
        <option value= option 1> Option 1 </option> 
        <option value= option 2> Option 2 </option>
    </select>

    etc....

    <?php  
    if(isset($_GET['from'])){ $from = $_GET['from']; }
    if(isset($_GET['to'])){ $to = $_GET['to']; }
    $agenti = $_GET['agenti'];
    $task = $_GET['task'];
    $categorie = $_GET['categorie'];
    $clienti = $_GET['clienti'];
    $raw_results = mysql_query("SELECT distinct ch.employeename, ch.customername, ch.QuestionnaireName, ch.parentgroupname, 
                                ch.groupname, vd.visitdate, vd.customerowner from chestionare ch
                                inner join visitdetails vd on vd.visitid =  ch.visitid
                                WHERE vd.visitdate >= '".$_GET['from']."' AND vd.visitdate <= '".$_GET['to']."' OR 
                                 ch.employeename= '$agenti' OR ch.questionnairename= '$task' OR ch.parentgroupname= '$categorie' OR vd.customerowner= '$clienti'
                                    ") 
                                or die(mysql_error());

    if(mysql_num_rows($raw_results) > 0){ 
        while($results = mysql_fetch_array($raw_results)){ 
    ?>

            <tr>
                <td><?php echo '<a href="g_angajat.php?name='.$agenti.'&from='.$from.'&to='.$to.'&clienti='.$clienti.'&task='.$task.'&categorie='.$categorie.'">' ?>    <?php echo $results['employeename']; ?></a></td>
                .... table for each dropdown
            </tr>


      <?php  } }?>
有人能帮帮我吗? THX

1 个答案:

答案 0 :(得分:0)

像这样解决了:

 $employeename= $_GET['employeename'];

 <select name="employeename">
 <option value="%">All Employees</option>
 <option value="John"John</option>
 </select>
 ...... x 6 times with different name for each select

现在在mysql中:

 SELECT distinct ch.employeename, ch.customername, ch.QuestionnaireName,   ch.parentgroupname, 
 ch.groupname, vd.visitdate, vd.customerowner from chestionare ch
 inner join visitdetails vd on vd.visitid =  ch.visitid
  WHERE vd.visitdate >= '".$_GET['from']."' AND vd.visitdate <= '".$_GET['to']."' AND
  ch.employeename like '$employeename' AND ch.questionnairename like '$task' AND ch.parentgroupname like '$parentgroupname' AND vd.customerowner like '$customers'

结果: 如果您将从员工下拉菜单中选择,它将仅返回员工JOHN的结果。如果从同一下拉菜单中选择所有员工,它将返回所有员工的结果。对于其他所有下拉列表都是相同的tehnic,并且在组合时效果很好。

:))这么简单。