Submitting HTML Form Data to MySQL Using React and PHP

Submitting HTML Form Data to MySQL Using React and PHP

A Complete Guide to Securely Storing User Data with React and PHP

Introduction

As a developer, you might come across the need to create a web application that involves an HTML form for users to enter their data. In this tutorial, we will learn how to create an HTML form in React and submit it to save the data in a MySQL database using PHP. We will also cover how to validate the form data and protect against SQL injection attacks.

Prerequisites

Before starting, make sure you have the following installed on your system:

  • Node.js and NPM

  • ReactJS

  • Axios

  • PHP and MySQL

Setting up the React Project

To start, let's set up a new React project by running the following command in your terminal:

npx create-react-app react-form

After the project is created, navigate to the project directory and install the Axios dependency by running the following command:

npm install axios

Creating the Form Component

Next, let's create a new component called "Form" where we will place our HTML form. In your "src" folder, create a new file called "Form.js" with the following code:

import React, { useState } from "react";
import axios from "axios";

const Form = () => {
  // Set initial state for the form data
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    message: "",
  });

  // Handle form data changes
  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setFormData({ ...formData, [name]: value });
  };

  // Handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();

    // Make HTTP POST request to PHP script
    axios
      .post("/submit.php", formData)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleInputChange}
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleInputChange}
        />
      </div>
      <div>
        <label htmlFor="message">Message:</label>
        <textarea
          name="message"
          value={formData.message}
          onChange={handleInputChange}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default Form;

In this code, we use the useState hook to set the initial state for the form data. We also create functions to handle form data changes and submissions using Axios to make an HTTP POST request to our PHP script. The form itself is created using standard HTML tags and the onChange event is used to update the form data state when a user types in a field.

Creating the PHP Script

Now let's create the PHP script that will receive the form data and save it to the MySQL database. In your project directory, create a new file called "submit.php" with the following code:

<?php

$db_host = 'localhost';
$db_user = 'username';
$db_pass = 'password';
$db_name = 'database_name';

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

if (!$conn) {
  die('Database connection failed!');
}

$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$message = mysqli_real_escape_string($conn, $_POST['message']);

if (empty($name) || empty($email) || empty($message)) {
  echo 'Please fill in all fields.';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo 'Invalid email format.';
} else {
  $query = "INSERT INTO data (name, email, message) VALUES ('$name', '$email', '$message')";

  if (mysqli_query($conn, $query)) {
    echo 'Form submitted successfully!';
  } else {
    echo 'Error submitting form.';
  }
}

mysqli_close($conn);

?>

In the PHP script, we first establish a connection to our MySQL database using the mysqli_connect() function. We then retrieve the form data using $_POST and sanitize it using mysqli_real_escape_string().

Next, we validate the form data using PHP validation functions. If the form data is valid, we construct an SQL query to insert the sanitized form data into our MySQL database using mysqli_query(). Finally, we close the database connection using mysqli_close().

If there is an error during any of these steps, we display an appropriate error message using echo.

Now we have successfully submitted our form data from our React form component to our PHP script and inserted it into our MySQL database. We have also added validation and sanitation to prevent SQL injection attacks.

Displaying Success and Error Messages

Once the form is submitted and the data is processed, we need to provide feedback to the user indicating whether the data was successfully saved or if there was an error.

We will create two separate message components - one for success messages and one for error messages.

First, let's create a SuccessMessage component:

function SuccessMessage() {
  return (
    <div className="success-message">
      <p>Your data has been successfully saved!</p>
    </div>
  );
}

This component simply renders a paragraph element with a success message.

Now, let's create the ErrorMessage component:

function ErrorMessage(props) {
  return (
    <div className="error-message">
      <p>{props.message}</p>
    </div>
  );
}

This component takes in a "message" prop, which will be the error message that we want to display. It renders a paragraph element with the message.

We will render these message components conditionally based on whether the form was successfully submitted or if there was an error.

In the handleSubmit function, we will set a state variable called "formSubmitted" to true if the form was successfully submitted, and "errorMessage" to the error message if there was an error:

const handleSubmit = async (event) => {
  event.preventDefault();
  const formData = {
    name: name,
    phone: phone,
    email: email,
    message: messageText,
  };
  try {
    const response = await axios.post("submit.php", formData);
    console.log(response);
    setFormSubmitted(true);
  } catch (error) {
    console.error(error);
    setErrorMessage("There was an error submitting your data.");
  }
};

Finally, let's conditionally render the success and error messages in the Form component:

return (
  <div className="form-container">
    {formSubmitted && <SuccessMessage />}
    {errorMessage && <ErrorMessage message={errorMessage} />}
    <form onSubmit={handleSubmit}>
      {/* form fields */}
    </form>
  </div>
);

If the form is successfully submitted, the SuccessMessage component will be rendered. If there is an error, the ErrorMessage component with the appropriate message will be rendered.

Conclusion

In this tutorial, we learned how to create a form in React and submit the form data to a PHP script using Axios. We also implemented form validation and data sanitization to prevent SQL injection attacks.

We created separate components to display success and error messages to the user, providing feedback on the status of the form submission.

With this knowledge, you can create complex forms in your React applications and securely store the submitted data in a database.

Thank you for following along, and happy coding!

Did you find this article valuable?

Support Shital Mainali by becoming a sponsor. Any amount is appreciated!