首頁  >  文章  >  資料庫  >  如何在 PHP 表單中實作刪除按鈕以從 MySQL 表中刪除記錄?

如何在 PHP 表單中實作刪除按鈕以從 MySQL 表中刪除記錄?

Barbara Streisand
Barbara Streisand原創
2024-10-27 21:30:30730瀏覽

How to Implement a Delete Button in a PHP Form to Remove Records from a MySQL Table?

如何將刪除按鈕集成到PHP 表單中以從MySQL 表中刪除記錄

問題:

向由MySQL 表填充的HTML 表添加「刪除」選項的請求已證明不成功。目標是創建一個功能性刪除鏈接,觸發表單提交並從資料庫中刪除相應的行。

程式碼快照:

results.php :

<code class="php">// Fetch data from the database
$contacts = mysql_query("SELECT * FROM contacts ORDER BY ID ASC") or die(mysql_error());

// If results exist, display the table
if (mysql_num_rows($contacts) > 0) {
    // Table markup
    echo '<table id="contact-list">';

    // Table head
    echo '<thead><tr><th>Name</th><th>Email</th><th>Telephone</th><th>Address</th><th>Delete</th></tr></thead>';

    // Table body
    while ($contact = mysql_fetch_array($contacts)) {
        echo '<tr>';
        echo '<td>' . $contact['name'] . '</td>';
        echo '<td>' . $contact['email'] . '</td>';
        echo '<td>' . $contact['telephone'] . '</td>';
        echo '<td>' . $contact['address'] . '</td>';

        // Delete form
        echo '<td><form action="delete.php" method="post">';
        echo '<input type="hidden" name="name" value="">';
        echo '<input type="submit" name="submit" value="Delete">';
        echo '</form></td>';

        echo '</tr>';
    }

    // Table foot
    echo '</table>';
}</code>

delete.

<code class="php">// Define the deletion query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";

// Execute the query
mysql_query($query);

// Display a success or failure message based on the number of affected rows
if (mysql_affected_rows() == 1) {
    echo '<strong>Contact Has Been Deleted</strong><br /><br />';
} else {
    echo '<strong>Deletion Failed</strong><br /><br />';
}</code>

解:

問題在於將主鍵值(在本例中為名稱)傳遞給delete.php 腳本。若要修正此問題,刪除連結必須透過隱藏欄位或作為 URL 參數包含名稱值。

更新的程式碼:

以上是如何在 PHP 表單中實作刪除按鈕以從 MySQL 表中刪除記錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn