Creating Simple Form using PHP and MySql

HTML forms are an essential part of the web development process, allowing us to gather data from user inputs. We can use this data to send emails, change interfaces, layouts, or save it directly to a MySQL table.

Today, we will create a simple HTML form to collect a user’s name, email, and message text, and use PHP to save the collected data into a MySQL database table. This is a common scenario in web development where we often need to store user data.

Step 1: Create HTML Form

To create an HTML form, open your HTML editor and place the following code within the <body> tags of your HTML page. This is a plain HTML page; no server-side coding like PHP is required here. We will cover PHP in the next step.

123456
&lt;form method="post" action="process.php"&gt;
    Name: &lt;input type="text" name="user_name" placeholder="Enter Your Name" required /&gt;&lt;br /&gt;
    Email: &lt;input type="email" name="user_email" placeholder="Enter Your Email" required /&gt;&lt;br /&gt;
    Message: &lt;textarea name="user_text" required&gt;&lt;/textarea&gt;&lt;br /&gt;
    &lt;input type="submit" value="Submit" /&gt;
&lt;/form&gt;

As shown in the HTML above, the <form> tag contains input fields for the user’s name, email, and message. You can add more input fields to collect additional data. These fields can have attributes like name, type, maxlength, placeholder, etc. While we only use name, type, and required here, you can explore other attributes as needed by our project.

Step 2: PHP Process Page

Our HTML form is ready to collect user inputs. Now, we need a PHP page to process this data. PHP is a server-side language, performing tasks on the server without exposing logic to users unless there are errors or outputs.

The action attribute in the form points to process.php, meaning all input field values are sent there. Below is the code for process.php to capture and display the submitted data.

1234567891011121314
&lt;?php
// process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $u_name = filter_input(INPUT_POST, "user_name", FILTER_SANITIZE_STRING);
    $u_email = filter_input(INPUT_POST, "user_email", FILTER_SANITIZE_EMAIL);
    $u_text = filter_input(INPUT_POST, "user_text", FILTER_SANITIZE_STRING);

    echo "Hello " . htmlspecialchars($u_name) . "!, we have received your message and email " . htmlspecialchars($u_email) . ".&lt;br /&gt;";
    echo "We will contact you very soon!";
} else {
    header("Location: index.html");
    exit;
}
?&gt;

Step 2: PHP Validation

The code above captures and displays input values, but it’s vulnerable to attacks like cross-site scripting (XSS). For example, if someone enters Sanwebe in the name field, it could output a clickable link, potentially allowing malicious JavaScript to run on your site, which could steal user data or redirect visitors. Unless you intentionally want to store HTML in the database (e.g., for a rich text editor), you should sanitize inputs to remove harmful content and validate them to ensure they meet your requirements.

12345678910111213141516171819202122232425262728293031323334
&lt;?php
// process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $u_name = filter_input(INPUT_POST, "user_name", FILTER_SANITIZE_SPECIAL_CHARS);
    $u_email = filter_input(INPUT_POST, "user_email", FILTER_SANITIZE_EMAIL);
    $u_text = filter_input(INPUT_POST, "user_text", FILTER_SANITIZE_SPECIAL_CHARS);

    $errors = [];
    if (empty($u_name)) {
        $errors[] = "Please enter your name";
    }
    if (empty($u_email) || !filter_var($u_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address";
    }
    if (empty($u_text)) {
        $errors[] = "Please enter a message";
    }

    if (!empty($errors)) {
        echo "&lt;h3&gt;Errors:&lt;/h3&gt;&lt;ul&gt;";
        foreach ($errors as $error) {
            echo "&lt;li&gt;$error&lt;/li&gt;";
        }
        echo "&lt;/ul&gt;&lt;a href='index.html'&gt;Go back to form&lt;/a&gt;";
        exit;
    }

    echo "Hello " . htmlspecialchars($u_name, ENT_QUOTES, 'UTF-8') . "!, we have received your message and email " . htmlspecialchars($u_email, ENT_QUOTES, 'UTF-8') . ".&lt;br /&gt;";
    echo "We will contact you very soon!";
} else {
    header("Location: index.html");
    exit;
}
?&gt;

We use filter_input with FILTER_SANITIZE_SPECIAL_CHARS to clean user inputs by escaping special characters, preventing harmful code from being executed. We also validate that the name and message fields aren’t empty and that the email is properly formatted. The htmlspecialchars function ensures that any output displayed on the page is safe, converting special characters like < into harmless HTML entities. These steps protect against XSS and ensure reliable data.

Step 3: Storing Data in MySQL

Using phpMyAdmin, create a table to store user data. Run the following SQL to create a table called users_data.

1234567
CREATE TABLE IF NOT EXISTS `users_data` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `user_name` VARCHAR(60) NOT NULL,
    `user_email` VARCHAR(60) NOT NULL,
    `user_message` TEXT NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Now, update process.php to connect to MySQL and store the data using prepared statements for security.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
&lt;?php
// process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // MySQL credentials
    $mysql_host = "localhost";
    $mysql_username = "your_username"; // Replace with your MySQL username
    $mysql_password = "your_password"; // Replace with your MySQL password
    $mysql_database = "your_database"; // Replace with your database name

    $u_name = filter_input(INPUT_POST, "user_name", FILTER_SANITIZE_STRING);
    $u_email = filter_input(INPUT_POST, "user_email", FILTER_SANITIZE_EMAIL);
    $u_text = filter_input(INPUT_POST, "user_text", FILTER_SANITIZE_STRING);

    if (empty($u_name)) {
        die("Please enter your name");
    }
    if (empty($u_email) || !filter_var($u_email, FILTER_VALIDATE_EMAIL)) {
        die("Please enter a valid email address");
    }
    if (empty($u_text)) {
        die("Please enter a message");
    }

    // Connect to MySQL
    $mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);

    if ($mysqli-&gt;connect_error) {
        die("Error: (" . $mysqli-&gt;connect_errno . ") " . $mysqli-&gt;connect_error);
    }

    $statement = $mysqli-&gt;prepare("INSERT INTO users_data (user_name, user_email, user_message) VALUES (?, ?, ?)");
    $statement-&gt;bind_param("sss", $u_name, $u_email, $u_text);

    if ($statement-&gt;execute()) {
        echo "Hello " . htmlspecialchars($u_name) . "!, your message has been saved!";
    } else {
        echo "Error: " . $mysqli-&gt;error;
    }

    $statement-&gt;close();
    $mysqli-&gt;close();
} else {
    header("Location: index.html");
    exit;
}
?&gt;

That’s it! process.php now securely collects and stores form data. To retrieve and display saved data, read the MySQLi Basic Usage article. I hope this article helps with your projects.