我在传递按钮ID以根据ID删除行时遇到问题。我该怎么做才能正确传递ID?
<form method="POST" >
<table border="1">
<tr>
<th>Student Name</th>
<th>Matric Number</th>
<th>IC Number</th>
<th></th>
<th></th>
</tr>
<?php
$link=mysqli_connect("localhost","root","") or die(mysqli_error());
mysqli_select_db($link,"myDataBase") or die(mysqli_error());
$query="Select * From student" or die(mysqli_error());
$result=mysqli_query($link,$query);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["matric"]."</td><td>".$row["ic"]."</td>
<td><input type=button value=Update></td><td><input type=submit value=Delete name=delete ><input type=hidden name=id value=".$row["id"]." ></td></tr>";
}
}else{
die("0 results");
}
if (isset($_POST['delete'])){
echo $did=$_POST['id'];
$query="Delete From student where id='$did'";
$result=mysqli_query($link,$query);
}
?>
</table>
</form>
答案 0 :(得分:0)
您需要更改查询:
$query="Delete From student where id=$did";
代替
$query="Delete From student where id='$did'";
答案 1 :(得分:0)
问题是所有包含学生ID的隐藏字段都放在一种表单中。因此,单击任何删除按钮时,都会发布最后一个隐藏字段ID
。将form
标签分别放置在每一行的Delete
列中,然后仅发布单击的行ID。同样,将SELECT
查询放在DELETE
查询之后,以在删除后立即刷新HTML表。您还需要避免SQL注入。
<?php
$link = mysqli_connect( "localhost", "root", "" ) or die( mysqli_error() );
mysqli_select_db( $link, "myDataBase" ) or die( mysqli_error() );
// delete record
if( isset( $_POST['delete'] ) ) {
echo $did = $_POST['id'];
$query = $link->prepare( "DELETE FROM student WHERE id=?" );
$query->bind_param( "s", $did );
$query->execute();
}
// get all records
$query = "SELECT * FROM student" or die( mysqli_error() );
$result = mysqli_query( $link, $query );
?>
<table border="1">
<tr>
<th>Student Name</th>
<th>Matric Number</th>
<th>IC Number</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?php
if( $result->num_rows > 0 ) {
while( $row = $result->fetch_assoc() ) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["matric"] . "</td>";
echo "<td>" . $row["ic"] . "</td>";
echo "<td><input type=button value=Update></td>";
echo "<td><form method='POST'>
<input type=hidden name=id value=".$row["id"]." >
<input type=submit value=Delete name=delete >
</form>
</td>";
echo "</tr>";
}
} else {
die("0 results");
}
?>
</table>
您还可以为每行分别创建删除链接(即test.php?delete_id = 100),而不是创建form
和GET
ID以便在服务器端删除。