首页  >  文章  >  数据库  >  如何使用 PHP 实现删除按钮以从 MySQL 表中删除行?

如何使用 PHP 实现删除按钮以从 MySQL 表中删除行?

DDD
DDD原创
2024-10-28 04:25:01302浏览

How to Implement a Delete Button to Remove Rows from a MySQL Table Using PHP?

添加删除按钮以使用 PHP 从 MySQL 表中删除行

向 HTML 中显示的 MySQL 表行添加删除选项表中,您可以按照以下步骤操作:

  1. 检索 MySQL 数据: 使用如下查询从联系人表中获取数据:
<code class="php">$contacts = mysql_query("
        SELECT * FROM contacts ORDER BY ID ASC") or die(mysql_error());</code>
  1. 创建带有删除按钮的表格:输出包含数据的表格,在最后一列添加删除按钮:
<code class="php"><table id=&quot;contact-list&quot;>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Telephone</th>
            <th>Address</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
        //Iterate results and display data
        <?php while( $contact = mysql_fetch_array($contacts) ) : ?>
            <tr>
                <td><?php echo $contact['name']; ?></td>
                <td><?php echo $contact['email']; ?></td>
                <td><?php echo $contact['telephone']; ?></td>
                <td><?php echo $contact['address']; ?></td>
                <td>
                    <form action='delete.php' method=&quot;post&quot;>
                        <input type=&quot;hidden&quot; name=&quot;name&quot; value=&quot;<?php echo $contact['name']; ?>&quot;>
                        <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Delete&quot;>
                    </form>
                </td>                
            </tr>
        <?php endwhile; ?>
    </tbody>
</table></code>
  1. 创建删除脚本:在delete.php中,处理提交的数据:
<code class="php">$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
// Execute the query to delete the record
mysql_query ($query);

// Handle success/failure scenarios
if (mysql_affected_rows() == 1) { 
    // Success: Contact deleted
    echo "<strong>Contact Has Been Deleted</strong><br /><br />";
} else { 
    // Failure: Deletion failed
    echo "<strong>Deletion Failed</strong><br /><br />";
} </code>
  1. 传递名称值:在HTML表中,传递使用隐藏字段将名称值传递给delete.php脚本或在URL中传递:
<code class="php"><form action='delete.php?name=&quot;<?php echo $contact['name']; ?>&quot;' method=&quot;post&quot;>
    <input type=&quot;hidden&quot; name=&quot;name&quot; value=&quot;<?php echo $contact['name']; ?>&quot;>
    <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Delete&quot;>
</form></code>

以上是如何使用 PHP 实现删除按钮以从 MySQL 表中删除行?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn