我制作了一个简单的HTML网页,其中包含员工名单(只有两个atm)。
<form method="post" action = "del.php">
<table border = "1">
<tr>
<th>Employee Name</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lavoratori";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT nome, id FROM operai";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<tr>";
echo'<td><input type = "checkbox" name = checkbox[]" value = '.$row['id']."<td>".$row['nome']."</td>";
echo"</tr>";
}
echo"</table>";
}
$conn->close();
?>
<input type = "submit" name = "delete" id = "delete" value = "Delete Records">
</form>
这是del.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lavoratori";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['delete'])){
$chkarr = $_POST['checkbox'];
foreach($chkarr as $id){
$sql = "DELETE FROM operai WHERE id = .$id.";
$result = $conn->query($sql);
}
header("Location: /test_purpose/home.php");
}
$conn->close();
?>
你们能告诉我怎么回事吗?我是PHP新手。 我想做的是从选中的复选框中删除特定的行。而且它不起作用,它将我重定向到主页,而没有明显删除任何内容。
答案 0 :(得分:0)
此行是错误的:
$sql = "DELETE FROM operai WHERE id = .$id.";
替换为:
$sql = "DELETE FROM operai WHERE id = {$id}";
您还需要考虑SQL Injection
:https://stackoverflow.com/a/60496/1403785