php web page form database
- User
php web page form database
- Assistant
php web page form database
Creating a PHP web page with a form that connects to a database is a common task for web developers. Below is a simple example that illustrates how to create a form, process the submitted data, and store it in a MySQL database.
First, you need to have a MySQL database setup. Assuming you have access to a MySQL server, you can create a database and a table using the following SQL commands:
CREATE DATABASE mydatabase;
USE mydatabase;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Create a file named form.html for the form where users will input their data. Save this file in your server's document root or a subdirectory where PHP files can be executed:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Form</title>
</head>
<body>
<h2>User Registration</h2>
<form action="process_form.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Create a file named process_form.php. This script will handle the form submission, validate the input, and save it to the database.
<?php
$servername = "localhost"; // Usually this is localhost
$username = "root"; // Your database username
$password = ""; // Your database password
$dbname = "mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare and bind
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
// Close connections
$stmt->close();
$conn->close();
}
?>
$servername, $username, $password) to match your actual database credentials.form.html and process_form.php) in a directory served by the server.form.html page in your web browser to test the form submission.This will allow you to test form submissions and see data stored in the database.
Not yet included in a published release.