Home >Backend Development >PHP Problem >Analyze how php+html implements a simple and easy-to-use deletion function
In web applications, deletion operations are essential. PHP, as a web-oriented programming language, provides a convenient way to perform deletion operations in the database. Combined with HTML forms, we can implement a simple and easy-to-use delete function.
First, let's take a look at how to build an HTML form so that users can enter the data they want to delete. Here is a simple example containing a text box and a submit button:
<html> <head> <title>删除数据</title> </head> <body> <form action="delete.php" method="post"> 输入要删除的数据:<input type="text" name="data"> <input type="submit" value="删除"> </form> </body> </html>
In this example, we have used the PHP file delete.php
to handle form submission. Next, we will introduce how to use the MySQL database in PHP to perform delete operations.
First, we need to connect to the MySQL database. This can be easily achieved using PHP's mysqli_connect
function. Here is a simple connection example:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "mydb"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检查连接是否成功 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } echo "连接成功"; ?>
Next, we need to get the data entered by the user to be deleted. We can use PHP's $_POST
superglobal array to get form data. The following is a sample code to obtain form data:
$data = $_POST['data'];
Next, we can use MySQL's "DELETE FROM" statement to perform the delete operation. The following is a simple deletion example:
$sql = "DELETE FROM mytable WHERE data = '$data'"; if (mysqli_query($conn, $sql)) { echo "删除成功"; } else { echo "删除失败: " . mysqli_error($conn); }
In this example, we assume that the data to be deleted is in a table named mytable
. We use the WHERE
clause to specify the data to be deleted. Please note that we used the $data
variable as a condition in the SQL statement. This variable is entered by the user.
Finally, we need to close the database connection in the PHP file. Here is a simple disconnect example:
mysqli_close($conn);
To sum up, it is not difficult to implement a delete statement using PHP and HTML. By combining an HTML form and a MySQL database, we can quickly build a practical delete function.
The above is the detailed content of Analyze how php+html implements a simple and easy-to-use deletion function. For more information, please follow other related articles on the PHP Chinese website!