基于所选复选框的SELECT查询

时间:2013-05-01 15:14:07

标签: php mysql arrays select checkbox

我有一个表单,用户可以选择可用的技能:

<form name="myForm" action="jssearch.php" method="post">

 <input type="checkbox" name="chk1[]" value="1">Helpdesk Support
 <input type="checkbox" name="chk1[]" value="2">DB Admin<br>
 <input type="checkbox" name="chk1[]" value="3">C++ Programming
 <input type="checkbox" name="chk1[]" value="5">HTML<br>
 <input type="checkbox" name="chk1[]" value="6">PHP<br>
 <input type="checkbox" name="chk1[]" value="7">Memory Dump Analysis<br>
 <input type="checkbox" name="chk1[]" value="8">SQL<br><br>

 <input type="submit" name="Update" value="Search">

</form> 

根据这些选择,我想针对多对多表运行查询,并显示包含所选技能的可用作业。

这是我目前的查询:

<?php

session_start();
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("jobsearch") or die(mysql_error());

$variable=$_POST['chk1'];
foreach ($variable as $variablename)
{
    $query = mysql_query(
       "SELECT jobs.jobid AS job_id, jobs.jobtitle AS
        job_title,jobs.salary AS salary_desc, GROUP_CONCAT(skills.Desc) AS skills_desc    
        FROM jobskillsjoin
        INNER JOIN jobs ON jobs.jobid = jobskillsjoin.JobID
        INNER JOIN skills ON skills.skill_id = jobskillsjoin.SkillID
        WHERE skills.skill_id = '".$variablename."'
        GROUP BY jobs.jobid
        ")
    or die(mysql_error());
}

echo "<table border='1'>
<tr>
<th>Job ID</th>
<th>Job Title</th>
<th>Skills required</th>
<th>Salary Offered</th> 
</tr>";

while($row = mysql_fetch_array($query))
{
    echo "<tr>";
    echo "<td>" . $row['job_id'] . "</td>";
    echo "<td>" . $row['job_title'] . "</td>";
    echo "<td>" . $row['skills_desc'] . "</td>";
    echo "<td>" . $row['salary_desc'] . "</td>"; 
    echo "</tr>";
}
echo "</table>";


?>

但会发生的是,只有最后选择的技能才能通过查询运行。我想显示所有“点击”。

我想我需要一个循环和一个数组,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

当您像提交的那样提交一个复选框时,它将成为PHP方面的一个数组。您需要在where子句中使用此数组。使用函数implode在字符串中转换数组并使用运算符“in”。所以你的where子句将是:

$query = mysql_query("SELECT jobs.jobid AS job_id, jobs.jobtitle AS
        job_title,jobs.salary AS salary_desc, GROUP_CONCAT(skills.Desc) AS skills_desc    
    FROM jobskillsjoin
    INNER JOIN jobs ON jobs.jobid = jobskillsjoin.JobID
    INNER JOIN skills ON skills.skill_id = jobskillsjoin.SkillID
    WHERE skills.skill_id in (". implode(",",$_POST['chk1']) .")
    GROUP BY jobs.jobid
    ")

这样,查询将返回所有已检查的技能。

要返回至少选择了一项技能的工作的所有技能,您需要将查询逻辑更改为:

SELECT j.jobid AS job_id, j.jobtitle AS
            job_title, GROUP_CONCAT(skills_Desc) AS skills_desc    
        FROM jobskillsjoin
        INNER JOIN jobs j ON j.jobid = jobskillsjoin.JobID
        INNER JOIN skills ON skills.skill_id = jobskillsjoin.SkillID
where exists(select 1 from jobskillsjoin where jobid = j.jobid and SkillID in (1,2))
        GROUP BY j.jobid;

请注意,我更改了查询。不要复制并粘贴到您的代码中。调整它以确保您不会错过任何东西。