如何使用foreach循环运行mysql查询?

时间:2017-06-02 12:35:10

标签: php jquery mysql

代码:

<script>
    $(document).ready(function(){
        $(".stream").click(function(){
            stream = $('.stream:checked').map(function() {
                return this.value;
            }).get().join(', ');
              console.log(stream);
              alert(stream);
            $.ajax({
                type:"POST",
                data:{"stream": stream},
                url:"stream.php",
                success:function(data){
                    $("#popular-colleges").html(data);
                }
            });
        });
    });
</script>

<input type="checkbox" name="stream" id="engineering" class="stream" value='engineering'>Engineering  
<input type="checkbox" name="stream" id="law" class="stream" value='law'>LAW<br/> 
<input type="checkbox" name="stream" id="medical" class="stream" value='medical'>Medical<br/>  
<input type="checkbox" name="stream" id="management" class="stream" value='management'>Management

stream.php

<?php 
    $streams = explode(",", $_POST['stream']);
    foreach ($streams as $stream) 
    {
        if($stream == 'engineering')
        {   
            $courses = "courses like '%,BTech,%' or courses like '%,MTech,%' or courses like '%,BCA,%'";
        }
        else if($stream == 'law') 
        {
            $courses = "courses like '%,LLB,%' or courses like '%,LLM,%' or courses like '%,BALLB,%'";     
        }
        else if($stream == 'medical') 
        {
            $courses = "courses like '%,MBBS,%' or courses like '%,MD,%' or courses like '%,BHMS,%'";        
        }
        else if($stream == 'management') 
        {
            $courses = "courses like '%,MBA,%' or courses like '%,BBA,%' or courses like '%,PGDM,%'";       
        }
    }
    echo "select * from all_colleges where ($courses) and city = '$city' order by priority desc ";   
?> 

这里我有四个带有类流的复选框,我将流值传递给stream.php,如工程,法律,医疗时检查多个复选框。现在我希望当我点击工程复选框时,它将运行工程查询,然后法律查询类似的医疗和管理。我想点击多个复选框多次查询。请帮帮我。

谢谢

1 个答案:

答案 0 :(得分:0)

// In javascript code replace 'get().join(', ');' with 'get().join(',');'

stream.php

$streams = explode(",", $_POST['stream']);
$city = 'indore';
$sql = [];
if (in_array('engineering', $streams)) {
    $sql[] = "courses like '%,BTech,%' or courses like '%,MTech,%' or courses like '%,BCA,%'";
}
if (in_array('law', $streams)) {
    $sql[] = "courses like '%,LLB,%' or courses like '%,LLM,%' or courses like '%,BALLB,%'";
}
if (in_array('medical', $streams)) {
    $sql[] = "courses like '%,MBBS,%' or courses like '%,MD,%' or courses like '%,BHMS,%'";
}
if (in_array('management', $streams)) {
    $sql[] = "courses like '%,MBA,%' or courses like '%,BBA,%' or courses like '%,PGDM,%'";
}

$query = "select * from all_colleges";

if (!empty($sql)) {
    $query .= ' WHERE ' . implode(' or ', $sql) . ' and city = '.$city.' order by priority desc ';
}

echo $query;