如何在php中删除一行?

时间:2016-12-16 05:59:49

标签: php mysql

我是用php制作的。当我选择一个类时,例如我选择class9,它会显示class9的表。我还在包含删除按钮的表中插入了一行来删除相应的行。现在我想删除行购买点击行中的按钮。我怎样才能做到这一点?
首先我从这个选项中选择一个班级,如下图所示; The image from which we select the class
然后将显示相应的表格。
 This is the image. When I click on the button, the corresponding row should be deleted.

<?php
include "connection.php";
?>

<!doctype html>
<html>
<head>
<title>KDR</title>
</head>

<body>


    <table border="2px" width="50%" height="auto">
    <tr>
        <th>No</th>
        <th>Name</th>
        <th>F/Name</th>
        <th>Age</th>
        <th>Delete</th>
    </tr>
    <?php
    $table = $_POST['formCountry'];
    $sql = "SELECT * FROM $table";
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc())
    {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['fname'] . "</td>";
        echo "<td>" . $row['age'] . "</td>";
        echo "<td><form method='POST' ><input type='submit' name='deletestudent' value='Delete'/></form></td>";
        echo "</tr>";
    }
    ?>
 </table>

 </body>

2 个答案:

答案 0 :(得分:2)

像这样的东西。也许需要稍微调整一下。

你的桌子按钮:

echo "<td><form method='POST' action="delete_row.php" ><input type='submit' name='deletestudent' value="'.$row['id'].'"/></form></td>";

在PHP(delete_row.php)中,您应该执行以下操作

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
         die("Connection failed: " . mysqli_connect_error());
    }

   if(isset($_POST['id']) and is_numeric($_POST['id']))
   {

        $delete = $_POST['id']

        $stmt = $conn->prepare("DELETE FROM YOURTABLENAME WHERE id = ?");
        $stmt->bind_param('i', $delete);
        $stmt->execute(); 
        $stmt->close();     
   }  

注意:未经过测试,我在这里使用mysqli_*

更新:正如@icecub建议你也可以使用隐藏字段来获取ID

echo "<td>
          <form method='POST' action='delete_row.php' >
               <input type='hidden' name='deletestudent' value='".$row['id']."'/>
               <input type='submit' value='Delete'/>
          </form>
     </td>";

答案 1 :(得分:0)

这是的方式,请参阅下面的评论,重要!

应该发送元素的当前id,所以当你单击按钮时 通过$ _GET ['id']获取元素ID;

<td><a href='?id=".$row['id']."'>delete</a></td>

if (isset($_GET['id'])) {
    //Throw query DELETE ... WHERE id = $_GET['id'];
}