我是SQL和PHP的新手,并尝试运行查询。
我正在努力把正确的操作员放进去,并且无法弄清楚为什么它不起作用!我一直在使用AND
OR
CASE
我有4个复选框:酒吧,俱乐部,餐馆,酒吧。
在我的数据库中,我的单选按钮上的每个单词都有一个名称列和一列。如果企业是一个Bar,那么在相应的Bar列中有一个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
如果没有检查,我希望结果显示所有选项的名称。当栏被选中时,只有经过俱乐部的酒吧,然后只有俱乐部等等
当酒吧和俱乐部被检查然后我想看所有酒吧和俱乐部等等
我如何得到我想要的结果?非常感谢您的帮助!
这是我目前正在处理的代码(我已将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>
如果未选中,则不会提交复选框。因此,在将其提交到查询之前,请检查其提交。将[]
添加到表单输入名称的末尾会将其作为数组提交,这不是您需要的。
<?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>