我是mysql和php的新手,我正在尝试设置一些参数来帮助我从表中删除一个条目,如果用户按下删除按钮。我目前已将其设置为用户可以使用部门,名称或课程编号搜索表格的位置。每个删除语句都是由他们使用的搜索准备的。
我遇到的问题是,当我创建我的删除语句时,我不知道如何确定SELECT语句选择的数据。下面显示了一小段代码。
if($_POST['radios'] == 0){
$sql = "SELECT * FROM classes where department LIKE '" . $_POST['search'] . "%';";
$select = 0;
$id = $sql;//problem area. Can't figure out how to pass the needed deparment info.
if($_POST['submit'] == "delete"){
if($select == 0){
mysqli_query($mysqli, "DELETE FROM classes WHERE department='".$id."'"); //need $id to match the correct department from table
mysqli_close($mysqli);
}
编辑:表格
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
`name` varchar(255),
`department` varchar(255),
`course_id` varchar(255),
PRIMARY KEY(`course_id`),
`start` time,
`end` time,
`days` varchar(255)
);
感谢您的帮助!
答案 0 :(得分:1)
这是删除特定“类”的一种简单方法。
Treat your buttons like a link,当您点击它时,它会重定向到特定页面,例如page.php?delete=ID
。
我假设您正在动态生成表格,因此您的代码有点类似于
<?php foreach ($classes as $class) : ?>
<tr>
<td><?= $class->name ?></td>
<td><?= $class->department ?></td>
<td><?= $class->course_id ?></td>
<td><?= $class->start ?></td>
<td><?= $class->end ?></td>
<td><?= $class->days ?></td>
<!-- note the use of type="button" as we don't want to submit anything -->
<!-- window.location.href is to redirect -->
<td><button type="button" onclick="window.location.href='page.php?delete=<?= $class->course_id ?>'">delete</button></td>
<td><button type="button">update</button></td>
</tr>
<?php endforeach ?>
然后在你的处理脚本page.php
中,你会做
if ($_POST['radios'] == 0){
$sql = "SELECT * FROM classes where department LIKE '" . $_POST['search'] . "%';";
// etc
}
// note we are using a GET method as we only did a redirection
if (!empty($_GET['delete'])) {
$id = $_GET['delete'];
mysqli_query($mysqli, "DELETE FROM classes WHERE course_id='".$id."'");
mysqli_close($mysqli);
// good idea to go back to previous page to see changes
header('Location: previousPage.php');
exit;
}
就是这样。
旁注:请阅读Lee Taylor关于SQL注入的评论,因为此代码容易受到攻击。开始了解prepared statements。