在PHP表的每一行上添加PHP中的删除按钮

时间:2017-04-07 20:11:46

标签: php html mysql

我正在尝试在每一行上添加一个删除按钮,以便在按下按钮时可以删除记录。我是PHP和MySQL以及Stack Overflow的新手。

下面是我从MySQL数据库中提取信息的表格。

       <table class="table" >
       <tr>
       <th> Staff ID </th>
       <th> Staff Name </th>
       <th> Class </th>
       <th> Action </th>

       </tr>   

       <?php

       while($book = mysqli_fetch_assoc($records)){

       echo "<tr>";
       echo "<td>".$book['Staff_ID']."</td>";
       echo "<td>".$book['Staff_Name']."</td>";
       echo "<td>".$book['Class']."</td>";
       echo "</tr>";
       }// end while loop

3 个答案:

答案 0 :(得分:7)

简单地使用PHP如下(你可以使用JS)

while($book = mysqli_fetch_assoc($records)){

echo "<tr>";
echo "<td>".$book['Staff_ID']."</td>";
echo "<td>".$book['Staff_Name']."</td>";
echo "<td>".$book['Class']."</td>";
echo "<td><a href='delete.php?id=".$book['Staff_ID']."'></a></td>"; //if you want to delete based on staff_id
echo "</tr>";
}// end while loop

delete.php文件中,

$id = $_GET['id'];
//Connect DB
//Create query based on the ID passed from you table
//query : delete where Staff_id = $id
// on success delete : redirect the page to original page using header() method
$dbname = "your_dbname";
$conn = mysqli_connect("localhost", "usernname", "password", $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record
$sql = "DELETE FROM Bookings WHERE Staff_ID = $id"; 

if (mysqli_query($conn, $sql)) {
    mysqli_close($conn);
    header('Location: book.php'); //If book.php is your main page where you list your all records
    exit;
} else {
    echo "Error deleting record";
}

答案 1 :(得分:2)

创建一个接收$ _GET ['id']的delete.php文件,然后运行sql以便在转到该页面时删除该记录。通过两种方式完成:像我在下面显示的锚标记,

或者创建一个按钮而不是一个锚点运行ajax(通过jquery)发送该id并运行上面提到的delete.php脚本。

table class="table" >
       <tr>
       <th> Staff ID </th>
       <th> Staff Name </th>
       <th> Class </th>
       <th> Action </th>

       </tr>   

       <?php

       while($book = mysqli_fetch_assoc($records)){

       echo "<tr>";
       echo "<td>".$book['Staff_ID']."</td>";
       echo "<td>".$book['Staff_Name']."</td>";
       echo "<td>".$book['Class']."</td>";
       echo "<td><a href='delete.php?id=".$book['Staff_ID']."'>Delete</a></td>";
       echo "</tr>";
       }// end while loop

答案 2 :(得分:0)

我建议你使用Ajax进行调用,比如@webDev,而不是调用PHP,用AjaxCall调用Javascript,然后使用JS隐藏/删除有问题的行,这样,用户无需重新加载整个页面。

您可以使用此代码而不是href补充您选择的答案:

keyCount

并在echo '<td><button onclick="deleteRow('.$book['Staff_ID'].')">Delete</button></td>'; 部分添加以下功能:

<head>