我正在从数据库中提取一个对象数组,并使用PHP迭代它们以显示一个表。表的每个结果行都可以从数据库中删除该特定记录。每一行也是一个对象,对象类型有一个方法可以从数据库中删除自己。
我现在面临的问题是如何让它在视图中发挥作用。现在,如果单击delete按钮,它将POST变量设置为" delete“,并重新加载侦听器进程检测变量并通过包含记录数据库id的隐藏输入启动删除的相同页面。
这一切都很好,但这些都是物体。难道每个对象都不能访问它自己的方法吗?似乎唯一的障碍是PHP脚本和HTML表单之间的相互作用。我的密码在下面。理想情况下,当按下delete按钮时,对象teamleader的特定实例可以运行其方法teamleader>delete_teamleader()。
<?php foreach($teamleaders as $teamleader) { ?>
<tr>
<td><?php echo $teamleader->first_name; ?></td>
<td><?php echo $teamleader->last_name; ?></td>
<td><img src="<?php echo '../img/' . $teamleader->photo;?>" alt="" class="img-fluid tiny-tl-img"></td>
<td><?php echo nl2br(substr($teamleader->bio, 0, 100));?>...</td>
<td><?php echo $teamleader->url_name;?></td>
<form action="index.php?a=edittl" method="post">
<td>
<input type="hidden" name="id" value="<?php echo $teamleader->id?>">
<input type="submit" class="btn btn-default" name="edit" value="Edit">
</td>
</form>
<form action="index.php" method="post">
<td>
<input type="hidden" value="<?php echo $teamleader->id?>" name="id">
<input type="submit" class="btn btn-danger" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this team leader?')">
</td>
</form>
</tr>
<?php } ?>发布于 2017-10-25 07:32:48
在您的例子中,我认为最好的解决方案是使用ajax/jQuery编辑或删除操作。您不需要像现在这样使用许多表单。
前端的代码如下:
<head>
<script src="jquery.min.js"></script>
</head>
...
<?php foreach($teamleaders as $teamleader) { ?>
...
<td><?php echo $teamleader->url_name;?></td>
<td>
<input type="submit" class="btn btn-default btn-edit" name="edit" value="Edit" data-teamleaderid="<?php echo $teamleader->id?>">
</td>
<td>
<input type="submit" class="btn btn-danger btn-delete" name="delete" value="Delete" data-teamleaderid="<?php echo $teamleader->id?>">
</td>
</tr>
<?php } ?>使用ajax/jQuery的代码是:
$(document).ready(function(){
$('.btn-delete').on('click',function(){
var _this = $(this);
var _teamleaderid = $(this).data('teamleaderid');
if (!confirm('Are you sure you want to delete this team leader?')) return false;
$.ajax(
url:'delete.php',
type:'post',
data: {
teamleaderid: _teamleaderid
},
dataType:'json',
success:function(data) {
if (data.return) {
$(_this).parent().parent().remove();/*Remove the current row in table html*/
alert('This teamleader has been deleted');
}
}
);
});
});后端的delete.php代码是:
<?php
... #connect database
$teamleader_id = filter_input(INPUT_POST,'teamleader');
$check_delete = $dbconn->query("DELETE from teamleader_table WHERE id={$teamleader_id}");
print json_encode('return'=>$check_delete);
die();
?>https://stackoverflow.com/questions/46925612
复制相似问题