PHP And React Contact Form With MySQL Database and AJAX

In every website, communication with users and their opinions and problems on the website is one of the main concerns of every webmaster. In this article, we will discuss how to create a PHP and React contact form with MySQL database and REST API. Using this system, you can receive users’ opinions, criticisms, and suggestions in the contact form and use them to improve your website. By combining these technologies, we can build a dynamic and interactive contact form that sends email notifications.

PHP React Contact Form With MySQL Database

A contact form is a great way to allow users to get in touch with you. Contact forms are essential components of websites that allow users to send messages or inquiries. It allows them to quickly and easily send you a message without having to use a traditional email client. With a contact form, you can easily capture information such as their name, email address, and message.

React is a popular JavaScript library for creating user interfaces. It is used by many developers to create dynamic, interactive web applications. One of the most popular applications of React and PHP is creating a contact form with a MySQL database. Contact forms are essential for any website, as they allow visitors to easily contact the site owner with questions or requests.

Creating a contact form in React and PHP with the MySQL database is relatively easy. React provides several components to be used to create a contact form, and PHP provides the backend and the database stores the sent data. These components include a form, an input field, a submit button, and a textarea for the user to enter their message.

However, we will not use these components in this article to create a contact form. The purpose of this article is to teach how to create a contact form with user-made components in React and PHP with MySQL database and not to use ready-made components. Using this article, you can design and develop your own component for this purpose.

To begin, create a new React component. This PHP API and React JS component will contain all of the elements of the contact form. Start by creating a form element, and then add an input field for the user’s name, an email field, and a textarea for their message. Finally, add a submit button to the form.

Once the form is created, you will need to add some functionality to it. React provides several methods that can be used to handle form submissions. In this case, you will want to use the onSubmit method. This method will be called when the user clicks the submit button, and it will take the data from the form and send it to the server.

Once the server receives the data, it can then be processed by PHP and a response can be sent back to the user. This response could be a confirmation message, or an error message if there were any problems with the form submission.

Creating a contact form in PHP and React is a simple task. With just a few lines of code, you can create a fully functional contact form that will allow visitors to easily get in touch with you.

What is PHP?

PHP (Hypertext Preprocessor) is a widely-used open-source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

With PHP, you can create powerful and dynamic web applications. You can connect to and manipulate databases, create images, create PDF files, and even talk to other computers. PHP runs on many different platforms (Windows, Linux, Unix, etc.) and is compatible with almost all servers used today (Apache, IIS, etc.).

PHP is free to download and use. It is easy to learn and runs efficiently on the server side.

PHP also has many frameworks and content management systems (CMS) available to help developers create websites quickly and easily. Examples of popular frameworks include Laravel, Symfony, CodeIgniter, and Zend Framework. Popular CMSs include WordPress, Drupal, and Joomla.

PHP is an incredibly powerful language that can be used to create dynamic and interactive websites. It is a great choice for web developers who want to create powerful web applications.

What is React?

React is a JavaScript library developed by Facebook for building user interfaces. It is used to create components, handle state and props, and utilize a virtual DOM. React is used to create interactive and stateful user interfaces that can be used to build single-page applications, mobile applications, and complex web applications.

React components are written using a declarative syntax that makes it easy to create components and manage state. Components are written using JavaScript and can be composed together to create complex user interfaces. React also utilizes a virtual DOM, which is a JavaScript object that is used to store and update the user interface. This allows React to update the user interface without having to reload the page.

React also includes an API that allows developers to easily create components, manage state and props, and handle events. React is used by many companies and organizations such as Airbnb, Netflix, and Twitter. It is also used to create popular libraries such as React Router and Redux.

React is a popular choice for web developers due to its flexibility and ease of use. It is also easy to learn and can be used to create complex user interfaces with minimal code. React is a powerful tool for creating modern web applications.

MySQL database design for the PHP and React contact form

All information entered by the user, including the user’s name, email, and message, will be stored in the MySQL database. In the PHP React JS contact form, some websites store information in the MySQL database, and in some systems, information is sent to the administrator’s email (such as Gmail). In this system, we store information in the MySQL database.

For this purpose, we create a database named contact_system and put the following table in it as follows.

php react contact form

This database has only one table named messages that store information and user comments. Because any user can enter his opinion in this form, it is not necessary for the user to be logged in.

Name, email, mobile number, company name, and message text are stored in the database. Because it is likely that the answer will be given to the customer, the email field cannot be empty. Since the purpose of the PHP and React contact form data is to receive user comments, the message field to store in the MySQL database cannot be empty.

To create tables, enter PHPMyAdmin and create your database. In this example, we will use the database named contact_system.

To create the User table of the contact form and system, enter the database you created and enter the following code in the SQL field.

CREATE TABLE IF NOT EXISTS `messages` (
  `name` text,
  `email` text NOT NULL,
  `mobile` varchar(14) DEFAULT NULL,
  `company` text,
  `message` text NOT NULL
)

In this section, since a user can send his comment many times, neither the primary key nor the uniqueness of the email field is needed.

Creation of a contact form with React JS, PHP, and MySQL database

The contact form uses React as the front end, PHP as the back end, and MySQL as the database. React can be executed in any folder on your system by NodeJS, so the limitation is on PHP. Go to the path you gave when installing Wamp or Xampp. If you are using Wamp, go to the “www” folder and if you are using Xampp, go to the “htdocs” folder.

Open VS Code in this folder and enter the following code in the terminal section.

npx create-react-app hs-contact-system

This command will start installing the React project. The term hs-contact-system is the name of the project, you can change it to your desired name.

After installing React, open the hs-contact-system folder using VS Code.

Install React requirement components

Before we begin, make sure you have PHP and a server environment set up to handle PHP scripts. Additionally, you should have Node.js and npm installed for React development.

In order to use React to create the contact form, we need to install the components that need to be installed by entering the following commands in the terminal.

npm install react-dom
npm install react-router-dom

Database class

In the root folder of the project, create a folder called classes and create database.php inside it and open it.

Enter the following codes in database.php.

<?php
class Database
{
    private $server_name = 'localhost';
    private $database_username = 'root';
    private $database_password = '';
    private $database_name = 'contact_system';
    private $connection = null;

    public function insertMessage($message)
    {
        $this->connection = new mysqli(
            $this->server_name,
            $this->database_username,
            $this->database_password,
            $this->database_name
        );
        $this->connection->set_charset('utf8');
        $sql = $this->connection->prepare(
            'INSERT INTO `messages`(`name`, `email`, `mobile`, `company`, `message`) VALUES (?,?,?,?,?)'
        );
        $sql->bind_param(
            'sssss',
            $message['name'],
            $message['email'],
            $message['mobile'],
            $message['company'],
            $message['message']
        );
        if ($sql->execute()) {
            $sql->close();
            $this->connection->close();
            return true;
        }

        $error = $this->connection->errno;
        $sql->close();
        $this->connection->close();
        return $error;
    }
}

The database class, which is in charge of connecting to the database, is contained in this file. This function (insertMessage), saves the inserted message into the MySQL database.

This project is implemented in the form of three-layer programming, where the database.php file is actually the data layer.

API file

All requests are directed to the api.php file because this system operates as a REST API. Create a file called api.php in the project’s root folder and save the following codes there.

<?php
include './classes/database.php';

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', $uri);

$action = $uri[3];

$database = new Database();

if ($action === 'add') {
    $rest_json = file_get_contents('php://input');
    $_POST = json_decode($rest_json, true);

    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    $company = $_POST['company'];
    $message = $_POST['message'];

    if (
        $database->insertMessage([
            'name' => $name,
            'email' => $email,
            'mobile' => $mobile,
            'company' => $company,
            'message' => $message
        ])
    ) {
        return_json(['result' => 'Your message has been saved.']);
    }
    else{
        return_json(['result' => 'Your message was not saved.']);
    }
}

return_json(['status' => 0]);

function return_json($arr)
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: *');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($arr);
    exit();
}

All requests are sent to this file, which is as follows.

In three-layer programming, this api.php file is actually the business layer.

The add action gets client information from the user interface (React) and sends it to the database. The result will be sent to the user interface in JSON format.

In this file, you can check the user’s input information for the correctness of the data. For example, check whether the user has entered the email correctly or not. Never trust user-submitted data. In an article entitled PHP Validation And Sanitization, we have investigated the validation of input data in PHP language.

File index.js

By default, all React projects start executing codes from the index.js file. Open the index.js file and put the following codes in it.

import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'
import { BrowserRouter, Route, Routes } from 'react-router-dom'

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
)

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()

App.js file

Like the index.js file, React projects also have App.js file by default. Open this file and put the following codes in it.

import './App.css'
import { useState } from 'react'

function App() {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [mobile, setMobile] = useState('')
  const [company, setCompany] = useState('')
  const [message, setMessage] = useState('')
  const [resultMessage, setResultMessage] = useState('')

  const submitHandler = async (event) => {
    event.preventDefault()
    try {
      await fetch('http://localhost/hs-contact-system/api/add', {
        method: 'POST',
        body: JSON.stringify({
          name: name,
          email: email,
          mobile: mobile,
          company: company,
          message: message,
        }),
      })
        .then((respose) => {
          if (respose.ok) {
            return respose.json()
          }
          throw new Error('error')
        })
        .then((data) => {
          if (data.result) {
            setResultMessage(data.result)
            setName('')
            setEmail('')
            setMobile('')
            setCompany('')
            setMessage('')
          } else {
            //set error
          }
        })
    } catch (error) {
      console.log(error.message)
    }
  }

  return (
    <div className="App" style={{ marginTop: '15px', marginBottom: '15px' }}>
      <div
        style={{
          maxWidth: '600px',
          marginLeft: 'auto',
          marginRight: 'auto',
          textAlign: 'left',
        }}
      >
        <form
          className="contact-form"
          onSubmit={submitHandler}
          style={{
            border: '1px solid #333',
            padding: '10px',
          }}
        >
          <div style={{ display: 'flex', marginTop: '15px' }}>
            <div style={{ width: '50%' }}>
              <label style={{ width: '100%' }}>Name</label>
              <input
                style={{ width: '100%', padding: '5px' }}
                type="text"
                value={name}
                onChange={(event) => {
                  setName(event.target.value)
                }}
              />
            </div>
            <div style={{ width: '50%' }}>
              <label style={{ width: '100%' }}>Email</label>
              <input
                style={{ width: '100%', padding: '5px' }}
                type="text"
                value={email}
                onChange={(event) => {
                  setEmail(event.target.value)
                }}
              />
            </div>
          </div>
          <div style={{ display: 'flex', marginTop: '15px' }}>
            <div style={{ width: '50%' }}>
              <label style={{ width: '100%' }}>Mobile</label>
              <input
                style={{ width: '100%', padding: '5px' }}
                type="text"
                value={mobile}
                onChange={(event) => {
                  setMobile(event.target.value)
                }}
              />
            </div>
            <div style={{ width: '50%' }}>
              <label style={{ width: '100%' }}>Company</label>
              <input
                style={{ width: '100%', padding: '5px' }}
                type="text"
                value={company}
                onChange={(event) => {
                  setCompany(event.target.value)
                }}
              />
            </div>
          </div>
          <div style={{ marginTop: '15px' }}>
            <label style={{ width: '100%' }}>Message</label>
            <textarea
              style={{ width: '100%', padding: '5px' }}
              value={message}
              rows={10}
              onChange={(event) => {
                setMessage(event.target.value)
              }}
            />
          </div>
          <input
            type="submit"
            value="Send"
            style={{
              padding: '15px',
              background: '#333',
              color: '#fff',
              border: 'none',
              marginTop: '15px',
              cursor: 'pointer',
            }}
          />
        </form>
        {resultMessage && (
          <div style={{ marginTop: '15px' }}>{resultMessage}</div>
        )}
      </div>
    </div>
  )
}

export default App

This file contains all the codes related to the form that the user must see. In this form, after the user enters the information and clicks the Send button, the information is sent to the API by the submitHandler function. This process of sending and receiving is done by AJAX technology, the basics of which you can read in the article How to use AJAX in WordPress.

In this file, you can check the user’s input information for the correctness of the data. For example, check whether the user has entered the email correctly or not.

Run the contact form and System (PHP, React, MySQL, and REST API)

The project is ready to run in this section, just enter the following command in the VS Code terminal.

npm start

The project will run on localhost and port 3000.

Conclusion

The PHP and React contact form article is a series of React and PHP articles that examine how to register comments, criticisms, and suggestions by website users. With this method, you can design a beautiful contact form along with its combination with technologies such as Bootstrap or Tailwind.

You may like

Shopping Cart