我正在尝试为宿舍创建一个房间可用性检查页面,我遇到了问题。
我有一个数据库,其中有一个名为' rooms'列出所有类型的房间:
我创建了一个代码,用PHP生成数据库中的房间列表,我想要" +"和" - "用于在特定房间的已使用列中添加或删除一个单元的按钮。我该怎么做?
这是我的代码:
<!-- SOME HTML/PHP THAT WORKS -->
<?php if ($roomlist->num_rows > 0) {
// output data of each row
while($room = $roomlist->fetch_assoc()) {
$roomid = $room["id"]; ?>
<div>
<!-- SOME OTHER HTML/PHP THAT WORKS -->
// THE ISSUE IS BELOW, IT SHOWS THE CORRECT AMOUNT BUT $room["used"] DOES NOT UPDATE
<div>
Used: <?php echo $room["used"] . " / " . $room["capacity"] ?>
</div>
<div>
<form action="" method="POST">
<input type="submit" name="remove" value="-" />
<input type="submit" name="add" value="+" />
<?php
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
?>
</form>
</div>
</div>
</div>
<?php }
} else {
echo "0 results";
} ?>
答案 0 :(得分:0)
如果您将表单的操作设置为您的代码名称(例如,&#34; rooms.php&#34;),那么移动
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
直到顶部所以它在查询表以填充页面的其余部分之前更新表,它应该工作。现在,你的php在SELECT查询后更新表格以填充你的页面,所以它似乎没有更新。
我认为更好的方法是实现AJAX,这样你的表单就可以更新Used字段而无需重新加载页面。
答案 1 :(得分:0)
好吧,所以我最终想出了一个方法,所以我在这里发布给其他面临类似问题的人来克服它;)
以下是index.php中代码的相关部分:
<form action="update.php?id=<?php echo $roomid ?>&action=remove&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="remove" class="minus" value="-" />
</form>
<form action="update.php?id=<?php echo $roomid ?>&action=add&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="add" class="plus" value="+" />
</form>
update.php的代码:
if (isset($_REQUEST['used']) && isset($_REQUEST['id']) && isset($_REQUEST['capacity'])) {
$roomid = $_REQUEST['id'];
$used = $_REQUEST['used'];
$capacity = $_REQUEST['capacity'];
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
if ($used >= $capacity) {
header("location: index.php");
} else {
$newValue = $used + 1;
$add_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'remove') {
if ($used <= 0) {
header("location: index.php");
} else {
$newValue = $used - 1;
$remove_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
}
}