How to save reactjs form data in php mysql?

reactjs

Hello to all, welcome to therichpost.com. In this post, I will tell you, How to save reactjs form data in php mysql?Reactjs is a Javascript Library to build user interface.

I am making simple form submission example with reactjs and php mysql. We will save reactjs form data in php mysql database and this is very interesting.

Here are the example images:

reactjs_form

 

reactjs_form-data_in_phpmysql

Here is the complete working and tested code:
index.js file code:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Home from './home';
import { Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,Container, Row, Col, Jumbotron, Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
class Hello extends React.Component{
  render() {
    return (
  <Router>
            <Container>
      <Row>
      <Col xs="3">
      <h2>Therichpost</h2>
      <Navbar light expand="md">
            <NavbarBrand></NavbarBrand>
        <Nav vertical navbar>
              <NavItem>
                <Link to={'/home'}>Home</Link>
              </NavItem>
        </Nav>
      </Navbar>
      
      </Col>
          <Col xs="9">
      <h4><small>RECENT Pages Data</small></h4>
          <hr />
      <Switch>
      
                  <Route exact path='/' component={Home} />
          <Route exact path='/home' component={Home} />
               </Switch>
      </Col>
      
               <footer class="container-fluid">
        <center><p>Therichpost</p></center>
      </footer>
         </Row>
            </Container>
      
         </Router>
    );
  }
  }

  ReactDOM.render(<Hello />, document.getElementById('root'));
 home.js file code:
import React, { Component } from 'react';
import axios from 'axios';
class Home extends React.Component{
  constructor(props)
    {
      super(props);
      this.addFormData = this.addFormData.bind(this);
    }
  addFormData(evt)
    {
      evt.preventDefault();
    const fd = new FormData();
      fd.append('myUsername', this.refs.myUsername.value);
    fd.append('myEmail', this.refs.myEmail.value);
    var headers = {
            'Content-Type': 'application/json;charset=UTF-8',
            "Access-Control-Allow-Origin": "*"
        }
    axios.post('http://localhost/core_php.php', fd, headers
    ).then(res=>
    {
     alert(res.data.data);
    }
    );
    
  }
  render() {
    return (
  <div>
    <p>Home</p> 
  <h5>Enter Your Info for testing:</h5>
  <form>
    <div className="form-group">
    <input type="email" className="form-control" id="Email" aria-describedby="emailHelp" placeholder="Enter email" ref="myEmail" />
    <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div className="form-group">
    <input type="text" className="form-control" id="Username" placeholder="Enter Username" ref="myUsername" />
    </div>
    <button type="submit" className="btn btn-primary" onClick={this.addFormData}>Submit</button>
  </form>
  <br/>
  </div>
  
    );
  }
  }
  export default Home;
 core_php.php file code:
<?php 
$servername = "localhost";
$username   = "root";
$password   = "root";
$dbname     = "user";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
    $sql = "INSERT INTO userdata (email, username)
        VALUES ('".$_POST['myEmail']."', '".$_POST['myUsername']."')";
    if (mysqli_query($conn,$sql)) {
    $data = array("data" => "You Data added successfully");
        echo json_encode($data);
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

?>

 Now you are done with reactjs form data saving into php mysql. If you have any query with this post, then please comment below.

 

 

 

 

 

Comments

9 responses to “How to save reactjs form data in php mysql?”

  1. Ashish gupta Avatar
    Ashish gupta

    Hello Sir, Thank u providing me this post tutorial .
    I am new in react js . So i have a questions :-

    Q. What is the use or meaning of this line :—- – this.addFormData = this.addFormData.bind(this);

    Q. Is the necessary to json during the form submission.

    Please reply as soon as possible.

    Regards,
    Ashish Gupta

    1. Ajay Malhotra Avatar

      In simple means, we are getting the form fields values.

  2. michale Avatar
    michale

    We have to run react we use node server .
    For inserting data in phpmysql we have to run Apache and sql separately? .

  3. usama qayyum Avatar
    usama qayyum

    where you define themethod in form tag and what if i want to savethe data in php variable how we can do it

  4. Seb Avatar
    Seb

    what is your architecture ? Because i can’t bind my php file to my app.js file…

    Thanks

    1. Ajay Malhotra Avatar

      Can you please elaborate more?

  5. laila Avatar
    laila

    where do i add the core.php file?

    1. Ajay Malhotra Avatar

      Inside your Xampp folder.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.