In web development, forms are a common way for users to interact with websites. When users fill out a form and submit it, the data is sent to the server for processing. The PHP script on the server is responsible for handling the form data and performing the necessary database operations, such as inserting new records or deleting existing ones. This article will provide a detailed guide on how to insert and delete form data using PHP.
When a user submits a form, the data is sent to the server and processed by PHP. Before inserting the data into the database, we need to establish a database connection, extract the form data, and use an SQL query to insert the data. Below is an example of how to insert data:
<?php // Connect to the database $host = "localhost"; $username = "root"; $password = "123456"; $dbname = "mydatabase"; $conn = new mysqli($host, $username, $password, $dbname); if ($conn->connect_error) { die("Database connection failed: " . $conn->connect_error); } // Extract form data $name = $_POST["name"]; $age = $_POST["age"]; $email = $_POST["email"]; // Insert data into the database $sql = "INSERT INTO users (name, age, email) VALUES ('$name', '$age', '$email')"; if ($conn->query($sql) === TRUE) { echo "Data inserted successfully"; } else { echo "Data insertion failed: " . $conn->error; } // Close the database connection $conn->close(); ?>
The above code connects to the database, retrieves the form data using the $_POST superglobal, and inserts it into the database using the INSERT INTO SQL statement. If the insertion is successful, it will output "Data inserted successfully"; if it fails, an error message will be displayed.
In addition to inserting data, sometimes we need to delete records from the database. Below is an example of how to delete records:
<?php // Connect to the database $host = "localhost"; $username = "root"; $password = "123456"; $dbname = "mydatabase"; $conn = new mysqli($host, $username, $password, $dbname); if ($conn->connect_error) { die("Database connection failed: " . $conn->connect_error); } // Extract form data $id = $_POST["id"]; // Delete data $sql = "DELETE FROM users WHERE id = '$id'"; if ($conn->query($sql) === TRUE) { echo "Data deleted successfully"; } else { echo "Data deletion failed: " . $conn->error; } // Close the database connection $conn->close(); ?>
This code establishes a connection to the database, retrieves the "id" from the form, and uses the DELETE FROM SQL statement to remove the corresponding record from the database. If the deletion is successful, it will output "Data deleted successfully"; if it fails, an error message will be shown.
As shown in the examples above, handling form data insertion and deletion in PHP is not complex. By establishing a database connection, extracting form data, and using appropriate SQL queries, we can easily perform these operations. We hope this article helps you better understand PHP form handling.