How to Create a Responsive Form Using PHP, JavaScript, HTML, CSS, and MySQL

0
466

I'll provide a detailed guide on creating a responsive form using PHP, JavaScript, HTML, CSS, and MySQL. The guide will include:

Key Points Covered

  1. Frontend Form (HTML, CSS, JavaScript)

    • Responsive design
    • Form validation (JavaScript)
    • Error handling
  2. Backend Processing (PHP)

    • Form submission handling
    • Server-side validation
    • Security measures (SQL Injection prevention)
  3. Database Integration (MySQL)

    • Creating a database
    • Storing form data
    • Fetching and displaying submitted data
  4. Extra Features

    • AJAX for real-time validation
    • Success/error messages
    • Mobile-friendly UI

Step 1: Create the Database in MySQL

Before we create the form, let's set up the database.

Database Structure

CREATE DATABASE form_db;

USE form_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 2: Frontend - Responsive Form (HTML, CSS, JS)

HTML - index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Form</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <form id="registerForm" action="process.php" method="POST">
            <h2>Register</h2>

            <div class="input-group">
                <label for="name">Full Name</label>
                <input type="text" id="name" name="name" required>
                <small class="error"></small>
            </div>

            <div class="input-group">
                <label for="email">Email</label>
                <input type="email" id="email" name="email" required>
                <small class="error"></small>
            </div>

            <div class="input-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" required>
                <small class="error"></small>
            </div>

            <button type="submit">Submit</button>
        </form>
    </div>

    <script src="script.js"></script>
</body>
</html>

CSS - styles.css

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: #f5f5f5;
}

.container {
    width: 100%;
    max-width: 400px;
    background: white;
    padding: 20px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
}

h2 {
    text-align: center;
    margin-bottom: 20px;
}

.input-group {
    margin-bottom: 15px;
}

label {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
}

input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    width: 100%;
    padding: 10px;
    background: #28a745;
    color: white;
    border: none;
    cursor: pointer;
}

button:hover {
    background: #218838;
}

.error {
    color: red;
    font-size: 12px;
    display: block;
}

JavaScript - script.js (Client-Side Validation)

document.getElementById("registerForm").addEventListener("submit", function(event) {
    let valid = true;

    const name = document.getElementById("name");
    const email = document.getElementById("email");
    const password = document.getElementById("password");

    const nameError = name.nextElementSibling;
    const emailError = email.nextElementSibling;
    const passwordError = password.nextElementSibling;

    if (name.value.trim() === "") {
        nameError.textContent = "Name is required";
        valid = false;
    } else {
        nameError.textContent = "";
    }

    if (email.value.trim() === "" || !email.value.includes("@")) {
        emailError.textContent = "Valid email is required";
        valid = false;
    } else {
        emailError.textContent = "";
    }

    if (password.value.length < 6) {
        passwordError.textContent = "Password must be at least 6 characters";
        valid = false;
    } else {
        passwordError.textContent = "";
    }

    if (!valid) {
        event.preventDefault();
    }
});

Step 3: Backend - Processing Form Submission (PHP + MySQL)

PHP Script - process.php

<?php
$servername = "localhost";
$username = "root"; // Change if necessary
$password = "";
$dbname = "form_db";

// 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") {
    $name = trim($_POST["name"]);
    $email = trim($_POST["email"]);
    $password = trim($_POST["password"]);

    if (empty($name) || empty($email) || empty($password)) {
        die("All fields are required.");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die("Invalid email format.");
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $email, $hashedPassword);

    if ($stmt->execute()) {
        echo "Registration successful!";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>

Step 4: Viewing Submitted Data

Create a PHP script to view submitted users.

View Users - view_users.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_db";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users ORDER BY created_at DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table border='1'>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Created At</th></tr>";
    while ($row = $result->fetch_assoc()) {
        echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['email']}</td><td>{$row['created_at']}</td></tr>";
    }
    echo "</table>";
} else {
    echo "No records found.";
}

$conn->close();
?>

Conclusion

  • The form is fully responsive and secure.
  • JavaScript provides client-side validation.
  • PHP handles secure form submission with hashed passwords.
  • MySQL stores user data.
  • view_users.php displays registered users.

Would you like me to add more features like email verification or AJAX-based form submission? 

Rechercher
Sellect from all Catégories bellow ⇓
Lire la suite
HTML
Creating a Responsive Navbar with Advanced Features such as scroll indicators, animated icons, or extra UI components
I'll provide a step-by-step guide with full...
Par flowisetech 2025-02-21 12:11:16 0 420
HTML
How to create advance button in HTML, CSS And JavaScript
Creating an advanced button in HTML involves...
Par Motivegist 2025-03-06 21:54:53 0 388
Python
The Basics of Python to get started
Basics of Python 1. Introduction to Python...
Par flowisetech 2025-03-02 16:29:42 0 373
PHP
How to Connect PHP to MySQL: A Step-by-Step Guide
Connecting PHP to MySQL is essential for...
Par flowisetech 2025-02-19 13:02:03 0 458
Cybersecurity
How to Legally Hack and Get Paid for It
Ethical hacking is a legal and highly rewarding...
Par flowisetech 2025-03-12 13:52:03 0 977