article

Saturday, October 23, 2021

ReactJS PHP Mysql and Axios Add data and list data - axios get and axios post

ReactJS PHP Mysql and Axios Add data and list data - axios get and axios post

https://github.com/axios/axios

The componentDidMount() life-cycle hook. This is executed when your React component is inserted/mounted in the DOM.

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios

header("Access-Control-Allow-Origin: *"); add this CORS header to enable any domain to send HTTP requests to these endpoints:

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(150) NOT NULL,
  `city` varchar(150) NOT NULL,
  `country` varchar(150) NOT NULL,
  `job` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `contacts` (`id`, `name`, `email`, `city`, `country`, `job`) VALUES
(36, 'Cara Stevens', 'cairocoders@gmail.com', 'Olongapo City', 'Phil', 'coders'),
(37, 'Airi Satou', 'AiriSatou@gmail.com', 'Tokyo', 'Japan', 'Accountant'),
(38, 'Angelica Ramos', 'AngelicaRamos@gmail.com', 'London', 'United Kingdom', 'Chief Executive Officer'),
(39, 'Ashton Cox', 'AshtonCox@gmail.com', 'San Francisco', 'USA', 'Junior Technical Author');

ALTER TABLE `contacts`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `contacts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=40;

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
import axios from 'axios';

class App extends React.Component {
  state = {
    name: '',
    email: '',
    country: '',
    city: '',
    job: '',
    contacts: []
  }

  componentDidMount() {
    const url = 'http://localhost/devtest/reactjs/contacts.php/'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ contacts: data })
      console.log(this.state.contacts)
     })
  }

  handleFormSubmit( event ) {
      event.preventDefault();

      let formData = new FormData();
      formData.append('name', this.state.name)
      formData.append('email', this.state.email)
      formData.append('city', this.state.city)
      formData.append('country', this.state.country)
      formData.append('job', this.state.job)

      axios({
          method: 'post',
          url: 'http://localhost/devtest/reactjs/contacts.php/',
          data: formData,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
      .then(function (response) {
          //handle success
          console.log(response)
          alert('New Contact Successfully Added.');  
      })
      .catch(function (response) {
          //handle error
          console.log(response)
      });
  }

  render() {
    return (
      <div className="container">
        <h1 className="page-header text-center">Contact Management</h1>
        
        <div className="col-md-4">
            <div className="panel panel-primary">
                <div className="panel-heading"><span className="glyphicon glyphicon-user"></span> Add New Contact</div>
                <div className="panel-body">
                <form>
                <label>Name</label>
                <input type="text" name="name" className="form-control" value={this.state.name} onChange={e => this.setState({ name: e.target.value })}/>

                <label>Email</label>
                <input type="email" name="email" className="form-control" value={this.state.email} onChange={e => this.setState({ email: e.target.value })}/>

                <label>Country</label>
                <input type="text" name="country" className="form-control" value={this.state.country} onChange={e => this.setState({ country: e.target.value })}/>

                <label>City</label>
                <input type="text" name="city" className="form-control" value={this.state.city} onChange={e => this.setState({ city: e.target.value })}/>

                <label>Job</label>
                <input type="text" name="job" className="form-control" value={this.state.job} onChange={e => this.setState({ job: e.target.value })}/>
                <br/>
                <input type="submit" className="btn btn-primary btn-block" onClick={e => this.handleFormSubmit(e)} value="Create Contact" />
            </form>
                </div>
            </div>
        </div>

        <div className="col-md-8">  
        <h3>Contact Table</h3>
        <table className="table table-bordered table-striped">
        <thead>  
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Country</th>
            <th>City</th>
            <th>Job</th>     
        </tr>
        </thead>
        <tbody>
        {this.state.contacts.map((contact, index) => (
        <tr key={index}>
            <td>{ contact.name }</td>
            <td>{ contact.email }</td>
            <td>{ contact.country }</td>
            <td>{ contact.city }</td>
            <td>{ contact.job }</td>
        </tr>
        ))}
        </tbody>
        </table>
         </div>  

        </div>
    );
  }
}
export default App;
http://localhost/devtest/reactjs/contacts.php/
//http://localhost/devtest/reactjs/contacts.php/
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 
$id = '';

$con = mysqli_connect($host, $user, $password,$dbname);

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from contacts"; 
      break;
    case 'POST':
      $name = $_POST["name"];
      $email = $_POST["email"];
      $country = $_POST["country"];
      $city = $_POST["city"];
      $job = $_POST["job"];

      $sql = "insert into contacts (name, email, city, country, job) values ('$name', '$email', '$city', '$country', '$job')"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    if (!$id) echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    if (!$id) echo ']';
  } elseif ($method == 'POST') {
    echo json_encode($result);
  } else {
    echo mysqli_affected_rows($con);
  }

$con->close();

Related Post