Programming

React JS user registration with PHP and MySQL

Today we are going to talk about How to build React JS user registration with PHP and MySQL. First of all, I would like to give a small idea of React JS. React JS is a front-end JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

If you are good with HTMLCSS, and JavaScript it is very useful here. Let’s start our React JS project step by step.

First of all, you need to Download and Install Node.js. Then, Go to the location you hope to start the project and open the CMD and run the below code to install react.

npm install -g create-react-app 

Then run the below code to create your project.

create-react-app registration

After the project builds successfully go inside the project folder and open the project using npm start.

cd registration
npm start

Then you can see the output like below.

reactjs user registration with php and mysql
figure 01

Now open the project folder using Visual Studio Code editor. Then you can see project files like below.

reactjs user registration with php and mysql
figure 02

Here we mainly focus on the App.js and App.css files inside the src folder. Now you have to delete whole codes inside the App.js and App.css. We no need to that codes we have to practice step by step. Then type the below code inside the App.js as your practice and save it.


import './App.css';

function App(){
  return(
    <div>
    <h1>Registration Form</h1>
    </div>
  );
}


export default App;

Here in the first line, we have to import the App.css file for style purposes. So you can style your project using your CSS knowledge. Using the above code you can get output like below.

reactjs user registration with php and mysql
figure 03

Create Signup Page

In this article, we hope to create login and registration pages. So right-click on the src folder and create a new folder named “components” (like figure 04). In this folder, we are going to store the login component and signup component.

reactjs user registration with php and mysql
figure 04

Firstly, right-click on the “components” folder and create a new folder named “signup“. Then right-click on the “signup” folder and create two files named “signup.js” and “signup.css” like figure 05 and figure 06. Now your folder structure should look like figure 06.


And here I hope to use MATERIAL-UI to create the interfaces. Material-UI is a library that allows us faster and easier web development. First of all, we have to install the Material-UI library in our project. You can install this using npm or yarn like below.

// with npm
npm install @material-ui/core

// with yarn
yarn add @material-ui/core

Then we are ready to use Material -UI. So open the signup.js file and type the below code. If you are fresher, Do not think this is a complicated code. Here we use the material card. So we have to import Card, CardActions and CardContent before we use them. And if we use Button or something in the material library we have to import those. You can use many components inside the Material library by following the MATERIAL-UI website.

import './signup.css';
import React from 'react';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import { Component } from 'react';

class Signup extends Component() {
 render(){
  return (
    <div className="card">
    <Card>
      <CardContent>
        <h1>Registration Form here</h1>
      </CardContent>
      <CardActions>
        <Button> Button </Button>
      </CardActions>
    </Card>
    </div>
  );
 }
}


export default Signup;

In the 10th line I used className=”card”. Using className we can add CSS styles from the signup.css file like below. So type this code in your signup.css file.

.card{
    padding-top: 100px;
    display: flex;
    justify-content: center;
    flex-direction: row;
}

Then our first step is ok. Now we have to add this to the App.js file otherwise we cannot see it in our output. So open the App.js and add your Signup component like figure 07.

reactjs user registration with php and mysql

Then refresh the page or use npm start. you can get output like below.

reactjs user registration with php and mysql
figure 07

Create Text Box Component

Now let’s create a new component to get text inputs. So right on the “src” folder and create a new folder named “core”. Inside the “core” folder create another folder named “textField”. Maybe you’ve wondered why I used two folders. Here I use the ” components” folder to store mains components like the signup component. And I use the “core” folder to store small components like text field components, button components. After that, you can see the “src” folder structure like below.

reactjs user registration with php and mysql
figure 08

In this project, we may need text boxes many times. So in the “React JS” we no need to create text boxes from time to time. We can use the same text box by changing properties according to our requirements.

Now open the textField.js and type the below code. In this code, you can see “props ” inside the TextBox function.  We can use these “props” to get the properties of the text boxes. Previously we discussed, we can use this text box many times. As an example, in the name text box, we can pass the label to this “props” parameter.

import './textField.css';
import React from 'react';
import TextField from '@material-ui/core/TextField';

function TextBox(props){
  return( 
  <div className="form">
   <TextField label={props.label} variant="outlined" style={{width:'100%'}} />
  </div>
    );
}

export default TextBox;

Then inside the textField.css type the below code.

.form{
    margin-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
}

Add a text field to signup component

When we add a text box in the signup, we can add like <TextField label=” Full Name”>. Let’s see how can we add this inside another component. So open signup.js and update your code according to the below code. Here I add CSS styles using the className tag. And you can see the inline CSS style in the 20th line. So, customize your styles as you wish.

import './signup.css';
import React from 'react';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import TextBox from '../../core/textField/textField';
import { Component } from 'react';

class Signup extends Component() {
 render(){
  return (
    <div className="card">
    <Card className="cardStyle" >
      <CardContent>
        <div className="signupText">SIGNUP</div>
        <TextBox label="Full Name"/>
      </CardContent>

      <CardActions className="CardActions" >
        <Button style={{background:'black',color:'white'}}> SIGNUP</Button>
      </CardActions>
      
    </Card>
    </div>
  );
 }
}


export default Signup;

Then update the signup.css file like below.

.card{
    padding: 50px;
    display: flex;
    justify-content: center;
    flex-direction: row;
}

.cardStyle{
    width: 500px;
    border-style:groove;
    border-color: rgba(0, 0, 0, 0.74);
}

.signupText{
    font-Weight:600px;
    text-Align:center;
    font-Size:20px
}

.CardActions{
    justify-content: center;
}

After that, you can see your signup page like this.

reactjs user registration with php and mysql
figure 09

When user registration, we have to get the user name, email, password, confirm password, phone number. So use the text field components into the signup.js file by changing the label property like we previously added “Full Name”.

<TextBox label="Email"/>
<TextBox label="Phone Number"/>
<TextBox label="Password"/>
<TextBox label="Conform Password"/>

Finally, You can see out-put like figure 10.

reactjs user registration with php and mysql
figure 10


Get the values in the text boxes by button click

First, we need to create a constructor inside the signup.js file. And then set the initial state and bind this to the events inside the constructor. Then open the signup.js and type the below code. Here I add code for only one text box, otherwise, code may be complicated to beginners. Here state uses to set initial values.

constructor(props){
  super(props);
  this.onChangeName= this.onChangeName.bind(this);

  this.onSubmit = this.onSubmit.bind(this);

  this.state ={
    name: '',
  }
}

Then we have to create five functions to assign our text box values. Here you can see one of them. So try to create the other four functions. I will show the full code finally. Here  ‘e’ is the argument of an event handler. Events are objects with certain properties. And ‘e.target.value’ is used to define the value property of some DOM element, in this case, that means the text entered in the input text field.

onChangeName(e){
  this.setState({
    name:e.target.value
  });
}


After that, we need to “onChange” property to assign the user inputs to the state and the “value” property used to display the value on the textbox.

 <TextBox label="Full Name" value={this.state.name} onChange={this.onChangeName}/>

When you set “value” and “onChange” like the above code, you have to update the TextBox component. So open the “textField.js” file and update TextField like below.

<TextField label={props.label} value={props.value} onChange={props.onChange} variant="outlined" style={{width:'100%'}} />

Now, Let’s create a new function to submit the data. Here ‘preventDefault()’ is called on the event when submitting the form to prevent a browser reload/refresh. When we click on the Signup button values assign to the ‘obj’ object. And ‘console.log(obj)‘ use to print ‘obj’ in the console.

onSubmit(e){
  e.preventDefault();
  const obj ={
    name:this.state.name
  };

 console.log(obj);
}

Then in the submit button, we have to call the ‘onSubmit()’ function like below.

<Button style={{background:'black',color:'white'}} onClick={this.onSubmit}>SIGNUP</Button>

After you completed the above steps, compare your updated signup.js file code with the following code.

import './signup.css';
import React from 'react';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import TextBox from '../../core/textField/textField';
import { Component } from 'react';


class Signup extends Component {

constructor(props){
  super(props);
  this.onChangeName= this.onChangeName.bind(this);
  this.onChangeEmail= this.onChangeEmail.bind(this);
  this.onChangePhone= this.onChangePhone.bind(this);
  this.onChangePassword= this.onChangePassword.bind(this);
  this.onChangePasswordconform= this.onChangePasswordconform.bind(this);
  this.onSubmit = this.onSubmit.bind(this);

  this.state ={
    name: '',
    email:'',
    phone:'',
    password:'',
    passwordConform:'',

  }
}

onChangeName(e){
  this.setState({
    name:e.target.value
  });
}

onChangeEmail(e){
  this.setState({
    email:e.target.value
  });
}

onChangePhone(e){
  this.setState({
    phone:e.target.value
  });
}

onChangePassword(e){
  this.setState({
    password:e.target.value
  });
}

onChangePasswordconform(e){
  this.setState({
    passwordConform:e.target.value
  });
}

onSubmit(e){
  e.preventDefault();
  const obj ={
    name:this.state.name,
    email:this.state.email,
    phone:this.state.phone,
    password:this.state.password,
    passwordConform:this.state.passwordConform,
  };

  console.log(obj);
}
render(){
  return (
    <div className="card">
    <Card className="cardStyle" >
      <CardContent>
        <div className="signupText">SIGNUP</div>

        <TextBox label="Full Name" 
               value={this.state.name} 
               onChange={this.onChangeName}/>

        <TextBox label="Email"  
               value={this.state.email} 
               onChange={this.onChangeEmail}/>

        <TextBox label="Phone Number" 
               value={this.state.phone} 
               onChange={this.onChangePhone}/>

        <TextBox label="Password" 
               value={this.state.password} 
               onChange={this.onChangePassword}/>

        <TextBox label="Conform Password" 
               value={this.state.passwordConform} 
               onChange={this.onChangePasswordconform}/>

        </CardContent>

      <CardActions className="CardActions" >
        <Button style={{background:'black',color:'white'}} onClick={this.onSubmit}> SIGNUP</Button>
      </CardActions>

    </Card>
    </div>
  );
}
}


export default Signup ;

Now right click on the page and select inspect (or click CTRL+SHIFT+I). Then input some data to the signup form and click on the signup button. You can see input values in the console.

reactjs user registration with php and mysql
figure 11

Install the Axios library

First of all, we have to install the Axios library. It is used to make requests to an API and return data from the API. So open the CMD inside the project folder and run the below code.

npm install axios --save

After the successfully installing Axios library import Axios in the signup.js like below.

import axios from 'axios';

Then type the below code inside the submit function in the signup.js file. And we have to create a folder named “reactProject” inside the XAMPP server “htdocs” folder.

axios.post('http://localhost/reactProject/insert.php',obj)
    .then(res=> console.log(res.data))
    .catch(error => {
      console.log(error.response)
  });

After that submit function should be like below. Here I used the if condition to check if the password matches the confirmed password.

onSubmit(e){
  e.preventDefault();

  if(this.state.password===this.state.passwordConform){
    const obj ={
      name:this.state.name,
      email:this.state.email,
      phone:this.state.phone,
      password:this.state.password,
      passwordConform:this.state.passwordConform,
    };
  
    axios.post('http://localhost/reactProject/insert.php',obj)
    .then(res=> console.log(res.data))
    .catch(error => {
      console.log(error.response)
  });

//To clear text box values 
  this.setState({
    name: '',
    email:'',
    phone:'',
    password:'',
    passwordConform:'',

  })
  }

  else{
    alert("Password mismatch")
  }
  
}

Create MySQL database

Now open the XAMPP and start Apache and MySQL. Then you can see the XAMPP control panel like below.

reactjs user registration with php and mysql
figure 12

Then type “http://localhost/phpmyadmin/ ” on your browser. After the PHPMyAdmin opened, click on the Databases.

figure 13

Now create a database named “reactjsUsers“.

figure 14

Then create a table named “users”. Here we need five columns to store id, name, email, phone, and password.

figure 15

Now give column names and data types like below. Here we have to set “sid” as Primary Key and Autoincrement.

figure 16

After that, you can see the table below.

figure 17

Implement the PHP REST API

Now go to the path “C:\xampp\htdocs” and create a new folder named “reactProject“. Then inside the “reactProject” folder, create a file named “connect.php”. That is used to connect the database. After that, open the “connect.php” file using any code editor and type the below code. Here you can change the username, password, and database name according to your project.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database= "reactjsusers";

// Create connection
$db = mysqli_connect($servername, $username, $password, $database);

// Check connection
if ($db->connect_error) {
  die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
?>

Then create another PHP file named “insert.php” and type the below code.

<?php
require 'connect.php';
header("Access-Control-Allow-Origin: http://localhost:3000");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
 $request = json_decode($postdata);
 
 
 $name = $request->name;
 $email = $request->email;
 $phone = $request->phone;
 $password = $request->password;
 $sql = "INSERT INTO users (name,email,phone,password) VALUES ('$name','$email','$phone','$password')";
 if(mysqli_query($db,$sql)){
  http_response_code(201);
 }
 else{
   http_response_code(422); 
 }
  
}
?> 

Then run the project, enter the sample data and submit. You can see the message “Connected successfully” in the console log.

reactjs user registration with php and mysql
figure 18

Now open the PHPMyAdmin and see the result. You can see, data is successfully added to the database.

figure 19

I think now you have a clear idea to build React JS User Registration. If you have any problem with this lesson comment on it. Let’s meet in the next lesson. And you can follow our Web Design Tutorial HERE.

Happy Coding!

How to start an Angular project

Nirodha Wickramarathna

Nirodha Wickramarathna is a dynamic full-stack software engineer, adept at crafting innovative digital solutions. With expertise in both front-end and back-end technologies, Nirodha brings a holistic approach to software development. Passionate about staying ahead in the tech world, Nirodha shares insights, coding tips, and experiences on this blog. Join the journey of coding excellence with Nirodha!

One thought on “React JS user registration with PHP and MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights