首頁  >  文章  >  資料庫  >  如何使用 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