Mountain Dew Mountain Dew - 9 months ago 39
MySQL Question

Delete MySQL row from PHP while loop

I have a while loop displaying my database columns and rows in table.


I want make a button which can delete specific MySQL row but unfortunately I can't select which of all rows have to be deleted simply because I use "while loop" to display my database content in HTML.


Providing picture for better understanding what I want to do:
enter image description here

So yeah, I want that when the green button is clicked - send MySQL query to delete this row (which is existing in my DB).

Providing code:

<?php
//CONECT TO MYSQL
include 'database.php';

//GET VALUES
$sql = "SELECT * FROM amountcontainer";
$result = $conn->query($sql);


if ($result->num_rows > 0)
{
//Table headlines - NOT A PHP
echo "<table class='moneytable'>
<tr>
<th style='background-color: #2d323a; color: white;'>Date</th>
<th style='background-color: #2d323a; color: white;'>Amount</th>
<th style='background-color: #2d323a; color: white;'>Reason</th>
</tr>";

// output data of each row
while($row = $result->fetch_assoc())
{

//RED //Make statement of amount red if it has a " - "
if(strpos($row['amount'],'-') !== false)
{

echo
"
<tr>
<th style='font-weight: normal;background-color: #ff9999;' class='row-time'>" . $row['time'] . "</th>
<th style='font-weight: normal;background-color: #ff9999;' class='row-amount'>" . $row['amount'] . "</th>
<th style='font-weight: normal;background-color: #ff9999;' class='row-reason'>" . $row['reason'] . "</th>
</tr>

";

}

//NORMAL //Make statement of amount normal if it doesn't have a " - "
else
{
echo
"
<tr>
<th style='font-weight: normal;' class='row-time'>" . $row['time'] . "</th>
<th style='font-weight: normal;' class='row-amount'>" . $row['amount'] . "</th>
<th style='font-weight: normal;' class='row-reason'>" . $row['reason'] . "</th>
</tr>

";

}


}
echo "</table>";
}

else
{
echo "0 results";
}

Answer Source

First, only use <th> elements for the table headers. For the actual data cells use the <td> element.

To allow deletion of individual database rows you can include links in your table. In your loop that creates the table rows:

                    <tr>
                        <td>" . $row['time'] . "</td>
                        <td>" . $row['amount'] . "</td>
                        <td>" . $row['reason'] . "</td>
                        <td><a href='?deleteId=$row[keyID]'>Delete</a></td> 
                    </tr>

In this case, when the "Delete" link is selected it calls your same script with a $_GET variable: "deleteId" which you can test for and if found, perform the delete of the row. You can also embed the table in an html form and add a submit button to a cell in each row, with the value of the submit set to the row id to delete.