使用复选框过滤PHP MySQL的记录

时间:2016-02-14 21:31:48

标签: php mysql checkbox

我是PHP和MySQL新手,所以请保持简单的答案!!!

我有一个数据库,列出了一堆退休社区及其提供的服务。我有一系列使用布尔值(tinyint)的字段,如果他们提供服务,他们得到1.如果他们没有,他们得到0。

我显示它很好,但现在我尝试使用复选框过滤列表。我也在按城市和州搜索(哪个工作),但是一旦我为复选框添加了代码,它就会失败。无论如何,它只显示所有记录。这就是我所拥有的:

HTML:

<form action="" method="post">
<fieldset><legend>Filter</legend>
    <p><label>City:&nbsp;</label><input type="text" name="by_city" /></p>
    <p><label>State:&nbsp;</label><input type="text" name="by_state" /></p>
    <p>
    <input type="checkbox" name="IndependentLiving" value="1" />    Independent Living<br>
    <input type="checkbox" name="AssistedLiving" value="1" /> Assisted Living<br>
    <input type="checkbox" name="SkilledNursing" value="1" /> Skilled Nursing<br>
    <input type="checkbox" name="MemoryCare" value="1" /> Memory Care<br>
    <input type="checkbox" name="ContinuingCareCommunity" value="1" /> Continuing Care Community<br>
    <input type="checkbox" name="Respite" value="1" />  Short-term/Respite<br>
    </p>
    <p><input class="button" type="submit" name="submit" value="Search" /></p>
</fieldset>     
</form>

PHP代码:

$by_city = $_POST['by_city'];
$by_state = $_POST['by_state'];
$IndependentLiving = $_POST['IndependentLiving'];
$AssistedLiving = $_POST['AssistedLiving'];
$SkilledNursing = $_POST['SkilledNursing'];
$MemoryCare = $_POST['MemoryCare'];
$ContinuingCareCommunity = $_POST['ContinuingCareCommunity'];
$Respite = $_POST['Respite'];



mysql_select_db('CommunityList');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$query = "SELECT * FROM Communities WHERE (City='$by_city') OR (State='$by_state') OR (IndependentLiving='$IndependentLiving') OR (AssistedLiving='$AssistedLiving') OR (SkilledNursing='$SkilledNursing') OR (MemoryCare='$MemoryCare') OR (ContinuingCareCommunity='$ContinuingCareCommunity') OR (Respite='$Respite')";
}
else {
$query = "SELECT * FROM Communities";
}
$result = mysql_query($query);

1 个答案:

答案 0 :(得分:0)

您在OR查询中使用SELECT表示OR,因此如果至少有一个WHERE匹配,则会返回记录。

你能做什么:

$postToColumnMaps = array('by_city' => 'City', 'by_state' => 'State');
$sqlWhereParts = array();
foreach ($postToColumnMaps as $postKey => $columnKey) {
    if (strlen($_POST[$postKey]) > 0) {
        $sqlWhereParts[] = $columnKey . ' = \'' . $_POST[$postKey] . '\'';
    }
}

$sqlWhere = implode(' AND ', $sqlWhereParts);

您可以使用此过滤器,然后

$query = "SELECT * FROM Communities WHERE " . $sqlWhere;

为了得到一个想法,我编写了它而没有测试。还要注意SQL注入,至少需要转义$_POST[$postKey]