如何通过Bootstrap Table编辑/删除MySQL数据,PHP如何识别待操作商品ID
解决方案
方案1:通过URL参数传递(最适合新手快速实现)
直接给操作按钮的<a>标签补充href属性,把商品ID作为URL参数传递,后端直接通过$_GET读取参数即可。
你可以直接替换原有循环输出表格的代码,修正后示例如下:
$query="select * FROM productadd"; $result= mysqli_query($connection, $query); if(mysqli_num_rows($result) > 0) { while($results = mysqli_fetch_array($result)){ $id = $results['id']; $name = $results['name']; $text = $results['text']; $price = $results['price']; $image = $results['image']; echo ' <tr> <td>'.$id.'</td> <td>'.$name.'</td> <td>'.$text.'</td> <td>$'.$price.'</td> <td> <img src="'.$image.'" style="display:block;" width="100%" height="100%"> </td> <td> <a class="add" href="product_add.php?id='.$id.'" title="Add" data-toggle="tooltip"> <i class="material-icons"></i> </a> <a class="edit" href="product_edit.php?id='.$id.'" title="Edit" data-toggle="tooltip"> <i class="material-icons"></i> </a> <a class="delete" href="product_delete.php?id='.$id.'" title="Delete" data-toggle="tooltip" onclick="return confirm(\'确定要删除该商品吗?\')"> <i class="material-icons"></i> </a> </td> </tr>'; } }
后端接收示例(以编辑页为例):
// product_edit.php 中获取要编辑的商品ID $id = (int)$_GET['id']; // 后续可以根据这个ID查询商品信息、执行更新操作
方案2:POST提交(更安全,适合敏感操作)
如果不希望参数暴露在URL中,可以给按钮添加自定义data-id属性存储商品ID,配合JS动态提交POST请求:
- 修改按钮代码,添加
data-id属性:
<a class="edit" data-id="'.$id.'" href="javascript:void(0)" title="Edit" data-toggle="tooltip"> <i class="material-icons"></i> </a>
- 页面加入JS监听点击事件提交表单:
document.querySelectorAll('.edit').forEach(btn => { btn.addEventListener('click', function() { const productId = this.getAttribute('data-id'); // 动态创建表单提交 const form = document.createElement('form'); form.method = 'POST'; form.action = 'product_edit.php'; const input = document.createElement('input'); input.type = 'hidden'; input.name = 'id'; input.value = productId; form.appendChild(input); document.body.appendChild(form); form.submit(); }) })
后端接收示例:
$id = (int)$_POST['id'];
注意事项
- 拿到ID后一定要做类型校验,比如转成int类型,避免SQL注入风险,执行数据库操作优先使用预处理语句
- 所有修改、删除操作前要做权限校验,避免用户随意修改参数操作不属于自己的商品
内容的提问来源于stack exchange,提问作者user14151807
相关产品推荐
相关产品推荐

