您好我是新手尝试使用PHP& DABL。
当我点击删除按钮时,它会从数据库中删除它,但仍显示在页面上。
如果我刷新页面或再次单击该按钮,则将其删除。
我知道我做错了什么但不确定是什么。
非常感谢
标记
<?php
require_once('includes/header.php');
$loginTypes = LoginTypes::getAll();
<ul>
<?php foreach ($loginTypes as $loginType){?>
<li><?php echo $loginType->type; $LoginTypeId = $loginType->login_type_id; ?>
<form action ="<?php $_SERVER['PHP_SELF']; ?>" method='post' >
<input type='hidden' name='<?php echo $LoginTypeId; ?>' id='<?php echo $LoginTypeId; ?>' />
<input type='submit' name='submit_<?php echo $LoginTypeId; ?>' id="submit_<?php echo $LoginTypeId; ?>" value='delete' />
</form>
</li>
<?php if(isset($_POST["submit_$LoginTypeId"])){
$delete = LoginTypes::retrieveByPK("$LoginTypeId");
$delete->delete();
}} ?>
</ul>
<?php require_once('includes/footer.php'); ?>
答案 0 :(得分:2)
因为您在实际删除项目之前显示该项目。将if
放在foreach
。
试试这个:
<?php
require_once('includes/header.php');
?>
<ul>
<?php
if(isset($_POST["submit_$LoginTypeId"])) {
$delete = LoginTypes::retrieveByPK("$LoginTypeId");
$delete->delete();
}
$loginTypes = LoginTypes::getAll();
foreach ($loginTypes as $loginType){ ?>
<li><?php echo $loginType->type; $LoginTypeId = $loginType->login_type_id; ?>
<form action ="<?php $_SERVER['PHP_SELF']; ?>" method='post' >
<input type='hidden' name='<?php echo $LoginTypeId; ?>' id='<?php echo $LoginTypeId; ?>' />
<input type='submit' name='submit_<?php echo $LoginTypeId; ?>' id="submit_<?php echo $LoginTypeId; ?>" value='delete' />
</form>
</li>
<?php } ?>
</ul>
<?php require_once('includes/footer.php'); ?>
答案 1 :(得分:1)
Alex Ciminian代码的略微修改版本。
主要更改是您处理POST变量的位置。这应该可行,但显然我不能在没有你的logintypes课程的情况下测试它。
由于它们都是不同的形式,因此您无需为提交按钮(或删除ID隐藏字段)使用唯一名称。我仍然倾向于通过将所有代码放在一个表单中来改进代码并使用复选框来标记要删除的代码,但这应该足够了。
<?php
require_once('includes/header.php');
if(isset($_POST['deleteSubmit'])) {
$delete = LoginTypes::retrieveByPK($_POST['LoginTypeId']);
$delete->delete();
}
$loginTypes = LoginTypes::getAll();
?>
<ul>
<?php
foreach ($loginTypes as $loginType){ ?>
<li><?php echo $loginType->type; $LoginTypeId = $loginType->login_type_id; ?>
<form action ="<?php $_SERVER['PHP_SELF']; ?>" method='post' >
<input type='hidden' name='LoginTypeId' value='<?php echo $LoginTypeId; ?>' id='<?php echo $LoginTypeId; ?>' />
<input type='submit' name='deleteSubmit' id="submit_<?php echo $LoginTypeId; ?>" value='delete' />
</form>
</li>
<?php } ?>
</ul>
<?php require_once('includes/footer.php'); ?>
答案 2 :(得分:0)
您应该在
之前执行删除操作$loginTypes = LoginTypes::getAll();