How to display a button for each row in a table

I have a MySQL database of booking records and I am displaying this in an HTML table. I was wondering how to add a button in every row of the table that will allow me to delete that row from the database.

<!DOCTYPE html> 
<html> 
    <head> 
        <h2> All bookings </h2> 
    </head> 
    <body> 
    <table class='striped white'>
        <thead>
          <tr>
              <th>ID</th>
              <th>First name</th>
              <th>Surname</th>
              <th>Date</th>
              <th>Time</th>
              <th>Action</th>
          </tr>
        </thead>

        <tbody>
            <?php
                if($result->num_rows>0){
                    while($row = $result->fetch_assoc()){
                        echo 
                        "<tr>".
                        "<td>". $row['id'] . "</td>" .
                        "<td>". $row['firstName'] . "</td>" .
                        "<td>". $row['surName'] . "</td>" .
                        "<td>". $row['date'] . "</td>" .
                        "<td>". $row['timeSlot'] . "</td>" .
                        "</tr>";
                    }
                } else{
                    echo 'no bookings';
                }
            ?>
        </tbody>
      </table>
    </body> 
</html>

Answer

You’ll need to add a cell with a URL that has code configured to run a DELETE command in your database. This is typically what atomic ID’s are used for. Lets assume the above table is in a file called table.php. Given this, we can adjust your first table cell to the following:

...
"<td>". $row['id'] . "<br /><a href="table.php?deleteId={$row['id']}">Delete Row</a></td>" .
...

Now when you click this link you’ll have a GET variable assigned in the $_GET superglobal array called “deleteId” that you can use to delete the row.

You’ll want to place this above your table so that any deletions reflect in the table each time you reload the page.

if (isset($_GET['deleteId'])) {
  // Sanitize input for SQL injection risk
  $deleteId = $mysqli->real_escape_string($_GET['deleteId'])

  if (!is_null($deleteId)) {
    // Just an example, you will need to correct this query and optionally use parameters vs. directly putting the variable in the SQL string
    $mysqli->query("DELETE FROM ... WHERE id = '$deleteId'");
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *