What are the key components needed to create a PHP form that saves data to a database?
To create a PHP form that saves data to a database, you will need the following key components: 1. HTML form with input fields for user data. 2. PHP script to process form data and save it to the database. 3. Database connection code to establish a connection to the database. Here is a sample PHP code snippet that demonstrates how to create a form that saves data to a database:
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Form processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
Keywords
Related Questions
- How can PHP be used to directly write CSV data into a MySQL database?
- What is the best method in PHP to read email addresses from multiple tables in a database and ensure no duplicates?
- What are the best practices for creating registration forms in PHP using Zend_Form or custom HTML/CSS, considering both styling and semantics?