如何向 PHP 表单添加删除按钮以从 MySQL 表中删除行

Luc*_*o79 3 html php mysql forms

我已将 MySQL 表的结果输出到 HTML 表。在最后一列中,我想添加一个删除选项,该选项调用另一个表单并从 MySQL 表中删除用户。但我似乎无法让它发挥作用。

这是我的结果页面代码:

<?php
                    
    $contacts = mysql_query("
        SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
    
    // If results
    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>
Run Code Online (Sandbox Code Playgroud)

而且,这是我的 delete.php 脚本

<?php

//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";

//sends the query to delete the entry
mysql_query ($query);

if (mysql_affected_rows() == 1) { 
//if it updated
?>

            <strong>Contact Has Been Deleted</strong><br /><br />
    
<?php
 } else { 
//if it failed
?>
    
            <strong>Deletion Failed</strong><br /><br />
    

<?php
} 
?>
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这不起作用。

Dev*_*hod 8

您必须在删除链接中传递一个变量。您必须在隐藏字段中传递<?php echo $contact['name']; ?>(值)或在以下位置传递该值:nameURL

代替

<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>
Run Code Online (Sandbox Code Playgroud)

<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>
Run Code Online (Sandbox Code Playgroud)