search

Home  >  Q&A  >  body text

How to add delete button in PHP form to delete a row from MySQL table

<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>
P粉174151913P粉174151913458 days ago486

reply all(2)I'll reply

  • P粉976737101

    P粉9767371012023-08-23 09:35:07

    Use javascript

    <input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="&laquo; 返回" />

    In delete.php

    $id=$_GET['id'];

    And put $id into your sql statement.

    reply
    0
  • P粉289775043

    P粉2897750432023-08-23 09:15:04

    You must pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?>(name value) in a hidden field or pass this value to URL

    Replace

    with

    <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>

    use

    <td class="contact-delete">
        <form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
            <input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
            <input type="submit" name="submit" value="Delete">
        </form>
    </td>

    reply
    0
  • Cancelreply