将删除按钮添加到 PHP 结果表

2021-12-28 00:00:00 html-table php mysql sql-delete

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

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user. I can't seem to get it to work though.

这是我的结果页面代码:

This is my code for the results page:

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

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

and, this is my delete.php script

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

很确定我只是遗漏了一些东西,但我不知道那是什么:(

Pretty sure I'm just missing something, but I can't figure out what that is :(

推荐答案

您必须在删除链接中传递变量.你必须通过 <?php echo $contact['name'];?> 隐藏字段中的名称值或在 URL

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

替换

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

随着

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

相关文章