如何将删除按钮集成到 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.php:
<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 参数包含名称值。
更新的代码:
<code class="php">// Within the table body loop in results.php echo '<td><form action="delete.php?name=' . $contact['name'] . '" method="post">';</code>
以上是如何在 PHP 表单中实现删除按钮以从 MySQL 表中删除记录?的详细内容。更多信息请关注PHP中文网其他相关文章!