我是SQL和PHP的新手,正在尝试运行查询。
我一直在努力寻找合适的操作员,却不知道为什么它不起作用!我一直在使用AND
OR
CASE
我有4个复选框:酒吧,俱乐部,餐馆,酒吧。
在我的数据库中,我的单选按钮上有一个name列和4个单词中的每个单词的列。 如果场所是酒吧,则在相应的酒吧列中为1。 如果企业是Pub,则在相应的Pub列中为1。 如果都是两者,则两者都将为1,依此类推
这是它的样子:
Name | Bar | Club | Restaurant | Pub
———————————————————————————————————————
McD | 0 | 0 | 1 | 0
KFC | 1 | 0 | 1 | 0
SPN | 1 | 1 | 1 | 1
GRG | 0 | 1 | 1 | 0
当没有任何检查时,我希望结果显示所有选项名称。 选中条后,则仅条 选中“俱乐部”后,则仅“俱乐部”等
选中Bars and Clubs之后,我要查看所有Bars and Clubs等,等等
如何获得想要的结果?非常感谢您的提前帮助!
这是我目前正在使用的代码(我将Bar变量留在了其中):
<?php
error_reporting(E_ALL);
$servername = "**";
$username = "**";
$password = "**";
$dbname = "**";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$getselectClub = implode(",",$_POST['selectClub']);
$getselectResturant = implode(",",$_POST['selectResturant']);
$getselectBar = implode(",",$_POST['selectBar']);
$sql = "SELECT id, name, locale FROM theList WHERE bar='$getselectBar' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<?php echo $row['id'];?>
<?php echo $row['name'];?>
<?php echo $row['locale'];?><br>
<?php }}} ?>
<form method="post">
Club: <input type='checkbox' name="selectClub[]" value="1" />
Resturant: <input type='checkbox' name="selectResturant[]" value="1" />
Bar: <input type='checkbox' name="selectBar[]" value="1"/>
<input type="submit" name="submit" value="submit" />
</form>
答案 0 :(得分:1)
如果未选中该复选框,则不会提交该复选框。因此,您需要先检查其提交,然后再将其添加到查询中。在表单输入名称的末尾添加[]
会将其提交为数组,这不是您所需要的。
<?php
error_reporting(E_ALL);
$servername = "**";
$username = "**";
$password = "**";
$dbname = "**";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["submit"])) {
$where = [];
$query = "";
if (!empty($_POST['selectClub'])) $where[] = "club=1";
if (!empty($_POST['selectRestaurant'])) $where[] = "restaurant=1";
if (!empty($_POST['selectBar'])) $where[] = "bar=1";
// check in case no boxes were checked
if (!empty($where)) {
$query = "WHERE " . implode(" OR ", $where);
}
$sql = "SELECT id, name, locale FROM theList $query";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "$row[id] $row[name] $row[locale]<br/>";
}
}
}
?>
<form method="post">
Club: <input type='checkbox' name="selectClub" value="1" />
Restaurant: <input type='checkbox' name="selectRestaurant" value="1" />
Bar: <input type='checkbox' name="selectBar" value="1"/>
<button type="submit" name="submit" value="1">Submit</button>
</form>