【发布时间】:2017-12-01 09:07:32
【问题描述】:
我有一个网站,我从一个程序中提取所有当前的活动用户,并且在管理面板中,我需要一个“终止开关”。
它从一个“在线”的 SQL 表中拉出用户,然后 php 将它变成一个数组。
<?php
$stack = array();
for($id = 1; $id <= 20; $id++)
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT * FROM online WHERE id = :id LIMIT 1');
$stmt->execute([':id' => $id]);
$user = $stmt->fetchObject('User');
array_push($stack, $user);
}
?>
这会遍历表并获取所有 ID 为 [1;20] 的在线用户。
然后它将 $user 堆叠在数组 $stack 中。
<table>
<thead><tr><th colspan="4"><span>Online right now</span></th></tr><tr><th colspan="4"> </th></tr><tr><th><span>E-Mail</span></th><th><span>Telefone</span></th><th><span>Unit ID</span></th></tr></thead>
<tbody>
<?php foreach ($stack as $num) : ?>
<?php if($num != null) : ?>
<tr>
<th><?=htmlspecialchars($num->email) ?></th>
<th><?=htmlspecialchars($num->telefone) ?></th>
<th><?=htmlspecialchars($num->unitid) ?></th>
<th><form action="thisPage.php" method="post"><input type="submit" name="killClick" value="Kill"/></form></th>
</tr>
<?php endif ?>
<?php endforeach ?>
</tbody>
</table>
这只是通过 $stack 将每个 $user 或 $num 分配给表中的一行,该行包含用户的电子邮件、电话号码、unitID 和 a 按钮。
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['killClick']))
{
$passedId = $num->id;
try
{
$db = Database::getInstance();
$stmt = $db->prepare('DELETE FROM online WHERE id = :id LIMIT 1');
$stmt->execute([':id' => $passedId]);
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
?>
上面的 PHP 位于同一页面上,并且在 foreach 循环之外。
所以目前当我按下按钮时,它会删除“在线”表中的所有用户......为什么?以及如何让它只删除我点击的用户?
【问题讨论】:
-
循环中的表单没有将任何 ID 值传递给删除函数 ~ 也许您应该在其中有一个隐藏字段,其中包含该特定条目的 ID,以便在表单被传递时传递发布
-
哦,是的,没想到!会试试的!