我有一个带有foreach array of items
的表。我想通过链接删除每个项目。在数据库中,表为“ users
”,行为“ id
”。
表的PHP代码:
<table class="blueTable">
<thead>
<tr>
<th>ID</th>
<th>USER</th>
<th>MAIL</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3">
<div class="links"><a href="#">«</a> <a class="active" href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">»</a></div>
</td>
</tr>
</tfoot>
<tbody>
<?php
$query = $db->query("SELECT * FROM users ORDER by id");
echo "<tr>";
while($row = $query->fetch_array()){
$id = $row['id'];
echo "<tr>"; //put <tr> opening code inside, not outside of while()
echo "<td>".$row['id']."</td>";
echo "<td>".$row['username']."</td>"; //remove <tr></tr>
echo "<td>".$row['email']."</td>"; //remove <tr></tr>
echo "<td><a href='delete($id)'>Delete</a></td>"; //remove <tr></tr>
echo "</tr>"; //close tr only once at the end
}
?>
</tbody>
</table>
删除代码的功能是:
function delete($id) {
$sql = 'DELETE FROM users
WHERE id = :id';
$q = $this->pdo->prepare($sql);
return $q->execute([':id' => $id]);
}
我将删除链接用于:
<a href='delete($id)'>Delete</a>
但是没有用。它提供了正确的ID,例如(delete(5)-,但并未删除它,因为它显示:
The requested URL /sistema-login/admin/delete(5) was not found on this server.
答案 0 :(得分:0)
我不知道您是否正在使用某种框架将url部分映射到函数参数,但是您可以使用
<a href='delete/<?= $id ?>'>Delete</a>
甚至
<a href='delete?id=<?= $id ?>'>Delete</a>
然后使用$_REQUEST
检索参数。
至少这会将参数发送到您的服务器。我不知道您如何将函数映射到路由,所以我不知道您是否获得了正确的URL。
答案 1 :(得分:0)
我认为您应该使用它来删除记录。在while
循环中
<a href='?id=<?= $id ?>'>Delete</a>
删除功能并像下面的代码一样使用$_REQUEST
。
if(isset($_REQUEST['id']) && !empty($_REQUEST['id']))
{
$dbh = connectDb();
$stmt = $dbh->prepare( "DELETE FROM users WHERE id =:id" );
$stmt->bindParam(':id', $_REQUEST['id']);
$stmt->execute();
}