How to add delete button in PHP form to delete a row from MySQL table
P粉174151913
2023-08-22 12:47:47
<p>I have output the results of the MySQL table into an HTML table. In the last column I want to add a delete option that calls another form and deletes the user from the MySQL table. But I can't seem to get it to work.</p>
<p>This is the code for my results page: </p>
<pre class="brush:php;toolbar:false;"><?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If there is a result
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table></pre>
<p>This is my delete.php script: </p>
<pre class="brush:php;toolbar:false;"><?php
//define query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//Send query to delete entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//If deletion is successful
?>
<strong>Contact deleted</strong><br /><br />
<?php
} else {
//If deletion fails
?>
<strong>Deletion failed</strong><br /><br />
<?php
}
?></pre>
<p>I can't figure out why this doesn't work. </p>
Use javascript
In delete.php
And put $id into your sql statement.
You must pass a variable in the delete link. You have to pass
Replace<?php echo $contact['name']; ?>
(name
value) in a hidden field or pass this value toURL
:with
use