所以我有这个PHP应用程序,您可以在其中创建任务并删除它们。问题是当我有多个任务时,所有删除任务链接将删除最新任务而不是您尝试删除的任务。例如,最新任务的id = 25。我想删除id = 18的任务,但是在单击删除链接时,它会删除id = 18的任务。
以下是任务视图的代码:
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id = $_SESSION['id'] = $row['id'];
$_SESSION['task'] = $row['task'];
$_SESSION['startdate'] = $row['startdate'];
$_SESSION['enddate'] = $row['enddate'];
//convert session startdate to a php date object
$startdate = new DateTime($_SESSION['startdate']);
$enddate = new DateTime($_SESSION['enddate']);
//echo task properties in a table
print "<div class='task'>";
print "<p><a href='editview.php?id=$id'>Edit Task</a> | <a href='delete.php?id=$id'>Delete Task</a></p>";
print "<p>Start Date: ".$startdate->format('d M Y')."</p>";
print "<p>Date to Complete By: ".$enddate->format('d M Y')."</p>";
print "<p>".$_SESSION['task']."</p>";
print "</div>";
}
以下是调用的删除函数(这也适用于editview函数,但它们都是同一个问题):
session_start();
//remove task from tasks table
$query="DELETE FROM tasks WHERE id=?";
//assign task id to variable id
$id = $_SESSION['id'];
try
{
//prepare the query
$stmt = $dbh->prepare($query);
//bind the id table value to the variable id
$stmt->bindParam(1,$id);
$stmt->execute();
}
答案 0 :(得分:3)
你有一个链接:
<a href='delete.php?id=$id'>
所以要获取您从$_GET
而非$_SESSION
$query="DELETE FROM tasks WHERE id=?";
//assign task id to variable id
$id = $_GET['id'];
并且避免循环中的Sessions,这不是必需的:
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id = $row['id'];
//convert session startdate to a php date object
$startdate = new DateTime($row['startdate']);
$enddate = new DateTime($row['enddate']);
//echo task properties in a table
print "<div class='task'>";
print "<p><a href='editview.php?id=$id'>Edit Task</a> | <a href='delete.php?id=$id'>Delete Task</a></p>";
print "<p>Start Date: ".$startdate->format('d M Y')."</p>";
print "<p>Date to Complete By: ".$enddate->format('d M Y')."</p>";
print "<p>".$row['task']."</p>";
print "</div>";
}
答案 1 :(得分:-1)
我认为你没有正确绑定参数,请尝试
session_start();
//remove task from tasks table
$query="DELETE FROM tasks WHERE id=:id";
//assign task id to variable id
$id = $_SESSION['id'];
try
{
//prepare the query
$stmt = $dbh->prepare($query);
//bind the id table value to the variable id
$stmt->bindParam(:id,$id,PDO::PARAM_INT);
$stmt->execute();
}