使用复选框筛选使用PHP的MySQL查询


Filtering MySQL Query using PHP using checkboxes

我在一家酒店管理公司的网站上工作。在投资组合页面上,我目前有一张谷歌地图,上面列出了所有酒店,还有一张来自数据库的酒店表。但是,我想要一个带有复选框的表格,复选框与酒店品牌相对应。选中复选框将只显示该品牌的酒店。我可以想出如何只选择一个品牌,但不能选择多个品牌。

这是表单的代码:

<form>
<div class="form-block">
<input type="checkbox" name="Courtyard" value="true" <?php if (isset($_GET["Courtyard"])) { echo "checked"; } ?> /> Courtyard<br />
<input type="checkbox" name="HolidayInnExpress" value="true" <?php if (isset($_GET["HolidayInnExpress"])) { echo "checked"; } ?> /> Holiday Inn Express<br />
<input type="checkbox" name="BestWestern" value="true" <?php if (isset($_GET["BestWestern"])) { echo "checked"; } ?> /> Best Western<br />
</div>
<div class="form-block">
<input type="checkbox" name="CrownePlaza" value="true" <?php if (isset($_GET["CrownePlaza"])) { echo "checked"; } ?> /> Crowne Plaza<br />
<input type="checkbox" name="HolidayInn" value="true" <?php if (isset($_GET["HolidayInn"])) { echo "checked"; } ?> /> Holiday Inn<br />
<input type="checkbox" name="SpringhillSuites" value="true" <?php if (isset($_GET["SpringhillSuites"])) { echo "checked"; } ?> /> Springhill Suites<br />
</div>
<div class="form-block">
<input type="checkbox" name="HamptonInn" value="true" <?php if (isset($_GET["HamptonInn"])) { echo "checked"; } ?> /> Hampton Inn<br />
<input type="checkbox" name="HomewoodSuites" value="true" <?php if (isset($_GET["HomewoodSuites"])) { echo "checked"; } ?> /> Homewood Suites<br />
<input type="checkbox" name="Independent" value="true" <?php if (isset($_GET["Independent"])) { echo "checked"; } ?> /> Independent Properties<br />
</div>
<button type="submit">Filter</button>

和MySQL查询显示表

    <?php
if (isset($_GET["BestWestern"])) {
  echo "Brand='"Best Western'"";
}
$result = mysql_query("SELECT Name, City, State, Website FROM markers WHERE Brand LIKE '%' ORDER BY City");
echo "<table border='1'>
<tr>
    <th>Hotel Name</th>
    <th>City</th>
    <th>State</th>
    <th>Website</th>
</tr>";
while($row = mysql_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['Name'] . "</td>";
    echo "<td>" . $row['City'] . "</td>";
    echo "<td>" . $row['State'] . "</td>";
    echo "<td><a href='" . $row['Website'] . "'>Visit Website</a></td>";
    echo "</tr>";
}
echo "</table>";
?>

如有任何帮助,我们将不胜感激。

最简单的方法是使用WHERE ... IN ()查询,而不是LIKE。例如

$brands = array('Brand X', 'Brand Y');
$sql = "SELECT ... WHERE Brand in ('" . implode("','", $brands) . "');";

请注意,这只是一个例子。它容易受到SQL注入攻击,不应按原样使用。