DEV Community

edupathhub.online
edupathhub.online

Posted on • Originally published at edupathhub.online

How can I use PHP to securely process a form submission and store the input data into a MySQL database

How to Safely Process a Contact Form with PHP and MySQL

When you submit a contact form, you want the data to land in your database without giving a hacker a backdoor. The easiest, most reliable way to do this is to use PHP’s prepared statements, which keep your SQL code separate from user input and automatically escape any dangerous characters. In short, bind the form values to placeholders, execute the statement, and you’re done.

For Most Students: The Classic Prepared‑Statement Pattern

Picture Maya, a junior computer‑science student who’s just finished her semester project. She’s built a simple HTML form with fields for name, email, and message, and now she needs to store the data in a local MySQL database. Maya’s professor told her to avoid raw SQL queries because they’re a recipe for injection attacks.

Maya opens her PHP file and writes:


$mysqli = new mysqli('localhost', 'root', '', 'contact_db');

$name = $_POST['name'];

$email = $_POST['email'];

$message = $_POST['message'];

$stmt = $mysqli->prepare('INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)');

$stmt->bind_param('sss', $name, $email, $message);

$stmt->execute();

$stmt->close();

$mysqli->close();

?>```



She tests it by submitting the form with a normal message and then with a string that looks like SQL. The database accepts both, but the malicious input is safely stored as plain text because the placeholders prevent it from being executed as code.

“I was nervous about SQL injection, but using bind_param made me feel like I had a safety net,” Maya says.

The key takeaway? Always use prepared statements when inserting user data. It’s a single line of code that protects you from a whole class of vulnerabilities.

## But If Your Situation Is Different: Using PDO, Handling File Uploads, and CSRF Tokens

Alex is a senior in information technology who’s building a portfolio website that includes a contact form and an optional file upload field for resumes. Alex’s professor wants him to demonstrate secure coding practices beyond simple prepared statements. Alex decides to switch to PDO for its flexibility and to add CSRF protection.

Alex’s PHP code now looks like this:



```php

try {



> **Refine your research writing with expert thesis editing** Sponsored Ensure the clarity, structure, and originality of your manuscript with our meticulous thesis editing services. Our editors review your work for research structure, citation formatting, and language accuracy. Get thesis editing support
>
> [Get thesis editing support](https://essaymarket.net?rt=xueF8aoD)

    $pdo = new PDO('mysql:host=localhost;dbname=portfolio', 'root', '');

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

    die('Connection failed: ' . $e->getMessage());

}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {

    $name = trim($_POST['name']);

    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

    $message = trim($_POST['message']);

    if ($email && $name && $message) {

        $stmt = $pdo->prepare('INSERT INTO contacts (name, email, message) VALUES (:name, :email, :message)');

        $stmt->execute([':name' => $name, ':email' => $email, ':message' => $message]);

        if (!empty($_FILES['resume']['name'])) {

            $target = 'uploads/' . basename($_FILES['resume']['name']);

            move_uploaded_file($_FILES['resume']['tmp_name'], $target);

            $fileStmt = $pdo->prepare('UPDATE contacts SET resume = :resume WHERE id = LAST_INSERT_ID()');

            $fileStmt->execute([':resume' => $target]);

        }

    }

}

?>```



Alex also generates a CSRF token at the start of the session and includes it as a hidden field in the form. By verifying the token on submit, he blocks cross‑site request forgery. The file upload is handled carefully: the script moves the file to a dedicated folder and records the path in the database, avoiding direct database writes of raw file data.

“Switching to PDO and adding CSRF tokens felt like adding armor to my code,” Alex reflects.

The actionable lesson: when your form does more than just text input—like file uploads or requires protection against CSRF—extend your prepared‑statement approach with PDO, proper validation, and token checks.

## Here’s How to Figure It Out: Step‑by‑Step Debugging and Validation

Sam, a sophomore in web design, is stuck after implementing the basic prepared statement. The form submits, but the data never shows up in the database. Sam suspects a connection issue but can’t find the error. He decides to add a systematic debugging process.

- **Check the database connection.** Use `mysqli_connect_error()` or PDO’s exception handling to capture connection problems.

- **Verify the table name and columns.** A typo in the table or column names will silently fail if you’re not checking the error.

- **Inspect the prepared statement.** After `prepare()`, call `errorInfo()` (PDO) or `errno` (mysqli) to see if the SQL is malformed.

- **Confirm the bind parameters.** Make sure the number and types of placeholders match the data you bind.

- **Log the query execution.** Temporarily echo or write to a log file the values being bound so you can see what’s actually going into the database.

- **Test with known safe input.** Submit a simple string like “test” and check the database directly to confirm the write operation works.

Sam follows these steps, discovers that his table name was misspelled, corrects it, and the data appears as expected. He also adds a simple `echo` after the execute call to confirm success.

“Seeing the error messages in real time saved me hours of guessing,” Sam notes.

Takeaway: always validate each step of your database interaction. Logging and echoing during development can reveal hidden mistakes before they become security issues.

## Quick Self‑Assessment

Question
Answer

Did you use a prepared statement or PDO?

Are you validating and sanitizing each form field?

Is there a CSRF token check in place?

Do you log or echo errors during development?

Have you tested with malicious input to confirm safety?

Fill in the blanks. If any answer is “No,” revisit the relevant section of this guide.

## Resources for Going Deeper

- Search for “PHP PDO prepared statements tutorial” to learn more about named parameters and advanced error handling.

- Look up “CSRF protection in PHP” to understand how to generate and verify tokens securely.

- Read up on “file upload security best practices” to avoid common pitfalls such as unrestricted file types.

- Explore “SQL injection case studies” to see real-world consequences and reinforce why prepared statements matter.

- Check “MySQL error codes” to interpret database errors quickly during debugging.

---

Originally published on [EduPath Hub](https://edupathhub.online/articles/how-can-i-use-php-to-securely-process-a-form-submission-and-store-the-input-data).
Enter fullscreen mode Exit fullscreen mode

Top comments (0)