Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a delete button in PHP on each row of a MySQL table

Tags:

html

php

mysql

I am trying to add a delete button on each row so that I can delete a record when the button is pressed. I am new to PHP and MySQL and Stack Overflow.

Below is my table which extract information from my MySQL database and that works.

       <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
like image 828
Hamzah Amir Avatar asked Jan 05 '23 05:01

Hamzah Amir


1 Answers

Simply using PHP as follows (You can use 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

In your delete.php file,

$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";
}
like image 139
BetaDev Avatar answered Jan 08 '23 01:01

BetaDev