[英]How to remove a query from an HTML table and database?
我有一个包含 2 个表的数据库:
第一个表“数据”与列(名称,电话,personid)
第二个表“链接”与列(linkid,link,personid)
Personid 是用“一对多”关系连接两个表的外键,当 DELETE 或 UPDATE 时它是“CASCADE”,所以一个人可以有 1 个以上的链接。
HTMl 表如下所示:
name phone links
jim 432443 link1
link2
link3
.....
_______________________
john 54545 link1
_______________________
... ..... .....
显示数据库包含在 html 表中的代码:
$state = $connect->prepare("SELECT data.personid, name, phone, link FROM data JOIN links ON data.personid = links.personid");
$state->execute();
$results = $state->fetchAll(PDO::FETCH_ASSOC);
$data = [];
foreach($results as $result) {
$data[$result['personid']] = [
'name' => $result['name'],
'phone' => $result['phone'],
'links' => [],
];
$data[$result['personid']]['links'][] = $result['link'];
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Links</th>
</tr>
</thead>
<tbody>
<?php
foreach ($data as $row) {
echo "<tr>";
echo "<th>".$row['name']."</th>";
echo "<td>".$row['phone']."</td>";
echo "<td>".implode('<br/>', $row['links'])."</td>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
?>
</table>
我想添加一个删除功能来删除其中一些数据,例如每个查询旁边的复选框和一个名为“删除选定”的按钮,例如,我知道如何添加复选框和按钮,但我不知道代码实现这个功能。
希望它适用于添加请检查此处显示的代码。
在 html 上包括:
<form action="action.php" method="POST">
<button type="submit">delete</button>
<table>
<thead>
<tr>
<th><input type="checkbox" name="check_select" readonly="readonly" onclick="toggleselect(this,'delete_data');"></th>
<th>Name</th>
<th>Phone</th>
<th>Links</th>
</tr>
</thead>
<tbody>
<?php
foreach ($data as $row) {
echo "<tr>";
echo '<input type="checkbox" class="check_box" name="checkbox_delete_data[]" value="'.$row['primary_id_of_your_table'].'">';
echo "<td>".$row['name']."</td>";
echo "<td>".$row['phone']."</td>";
echo "<td>".implode('<br/>', $row['links'])."</td>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
?>
</table>
</form>
在 JavaScript 中:
function toggleselect(source,chkbox_name)
{
checkboxes = document.getElementsByName('checkbox_'+chkbox_name+'[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
现在您可以访问 action.php 文件中选中的复选框,并使用它来删除查询。
例如:
<?php
if (isset($_POST["submit"])) {
$selected_check_boxes = implode(',', $_POST["checkbox_delete_data"]);
$query= $connect->prepare("Delete from table where table.primary id IN ($selected_check_boxes)");
$query->execute();
}
?>
我建议在 <form> 中制作整个表格,并在每个复选框中添加一些带有 personId 的“data-”属性。 然后使用javascript处理(提交表单时)这些属性并合并SQL查询,如
delete from data where personid (1,2,3, ...)
如果您需要更多帮助,我可以编写一些代码,但自己开发总是更好:)
干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.