To submit HTML form data in PHP and store it in a database, you need to follow these steps:
1. Create an HTML form:
- Start by creating an HTML form using the <form> tag.
- Specify the form method as "POST" or "GET" using the method attribute.
- Set the action attribute to the PHP file where you will process the form data.
- Add input fields with appropriate names and types.
Here's an example of an HTML form:
Html code:
<form method="POST" action="process.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
2. Create a PHP file to process the form data (e.g., "process.php"):
- Start by establishing a connection to your database.
- Retrieve the submitted form data using the $_POST superglobal variable.
- Sanitize and validate the input data to ensure it's safe and correct.
- Prepare and execute an SQL INSERT statement to insert the data into the database.
- Handle any errors that may occur during the database operation.
Here's an example of the PHP code to process the form data and insert it into a MySQL database:
php code:
<?php
// Establish database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
// Sanitize and validate the data (optional)
// Prepare and execute SQL statement
$sql = "INSERT INTO your_table (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error inserting record: " . $conn->error;
}
// Close the database connection
$conn->close();
?>
Replace the placeholders
'your_username',
'your_password',
'your_database', and
'your_table' with your actual database credentials and table name.
Make sure the PHP file (process.php in this example) is in the same directory as your HTML form file.
That's it! When the form is submitted, the PHP code will process the data and insert it into the specified database table.
