Search code examples
phphtmlmysqldelete-row

PHP and HTML Deleting


I simply just want a button in my table to delete the specific row but everything I search for ends up being some completely different way compared to how I have set it up.

<?php

// Connects to your Database and if it cant it dies
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// this selects the db
mysql_select_db("test", $con);

// this passes the query into the variable result
$result = mysql_query("SELECT * FROM items");

echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Quantity</th>
<th>Delete</th>
<tr>";

while($row = mysql_fetch_array($result))
   {
  echo "<tr>";
  echo "<td>" . $row['ID'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['quantity'] . "</td>";
  echo "<td>" . '<a href="delete.php">Delete</a>' . "</td>";
  echo "</tr>";
   }
echo "</table>";

mysql_close($con);
//end php
?> 

<html>
<body>

<form action="insert.php" method="post">
Name: <input type="text" name="Name" />
Quantity: <input type="text" name="Quantity" />
<input type='submit' name='add' value='add' />
</form>

</body>
</html>

i would like the hyperlink to delete the row is contained in.


Solution

  • You need to add the ID of the record you want to delete to the delete url, e.g.:

    echo "<td><a href=\"delete.php\?id={$row['ID']}">Delete</a></td>";
    

    Then, in your delete.php script, you'd do:

    <?php
    
    $id = intval($_GET['id']);
    $sql = "DELETE FROM yourtable WHERE id=$id";
    $result = mysql_query(sql);
    

    Of course, that's not a full script, but shows you the basics of what needs to be done. Be careful with using the passed-in value in your query - don't want to let an SQL injection hole ruin your day.

    However, be aware that using a 'GET' type query for this sort of thing is generally a bad idea. If this page gets spidered by Google (for one), you'll find that the simple act of spidering has nuked ALL of your records.