article

Wednesday, October 27, 2021

ReactJS Axios PHP Mysql CRUD (Create Read Update and Delete)

ReactJS Axios PHP Mysql CRUD (Create Read Update and Delete)

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

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

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';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  <App />,
  document.getElementById('root')
)
src/App.js
//src/App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Contact from './components/contact';
import Update from './components/update';
import Create from './components/create';

class App extends React.Component {
    render() {
        return (
            <Router>
            <div>
                <Route exact path='/' component={Contact} />
                  <Route path='/update/:id' component={Update} />
                <Route path='/create' component={Create} /> 
            </div>
            </Router>
        );
    }
}
export default App;
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" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/contact.js
//src/contact.js
import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Contact extends React.Component {
	constructor(props) {
		super(props);
		this.state = {contacts: []};
		this.headers = [
			{ key: 'id', label: 'Id'},
			{ key: 'name', label: 'Name' },
			{ key: 'email', label: 'Email' },
			{ key: 'country', label: 'Country' },
			{ key: 'city', label: 'City' },
			{ key: 'job', label: 'Job' }
			];
		this.deleteContact = this.deleteContact.bind(this);
	}
  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)
     })
  }
	
  deleteContact(id, event) { //alert(id)
	event.preventDefault();
	if(window.confirm("Are you sure want to delete?")) {
		axios({
			method: 'post',
			url: 'http://localhost/devtest/reactjs/contacts.php/?delete=' + id
		})
		.then(function (response) {
			//handle success
			console.log(response)
			if(response.status === 200) {
				alert("Website deleted successfully");
			}
		})
		.catch(function (response) {
			//handle error
			console.log(response)
		});
    }
  }    
	
	render() {
		return (
			<div className="container"><h1>ReactJS Axios PHP Mysql CRUD (Create Read Update and Delete) </h1>
			<p><Link to="/create" className="btn btn-primary btn-xs">Add New Contact</Link> </p>
        	<table className="table table-bordered table-striped">
					<thead>
						<tr>
						{
							this.headers.map(function(h) {
								return (
									<th key = {h.key}>{h.label}</th>
								)
							})
						}
						  <th>Actions</th>
						</tr>
					</thead>
					<tbody>
						{
							this.state.contacts.map(function(item, key) {
							return (
								<tr key = {key}>
								  <td>{item.id}</td>
								  <td>{item.name}</td>
								  <td>{item.email}</td>
                  	<td>{item.country}</td>
                  	<td>{item.city}</td>
                  	<td>{item.job}</td>
								  <td>
                    <Link to={`/update/${item.id}`} className="btn btn-primary btn-xs">Edit</Link>
                      
					<Link to="#" onClick={this.deleteContact.bind(this, item.id)} className="btn btn-danger btn-xs">Delete</Link>
								  </td>
								</tr>)
							}.bind(this))
						}
					</tbody>
				</table>
			</div>
		)
	}
}

export default Contact;
src/update.js
//src/update.js
import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Update extends React.Component {
  constructor(props) {
    super(props);
    this.state = {id: '', name: '', email: '', city:'', country:'', job:''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    axios.get('http://localhost/devtest/reactjs/contacts.php/?id=' + this.props.match.params.id)
    .then(response => response.data)
    .then((data) => {
      // handle success
      console.log(data);
      this.setState({ id: data.id, name: data.name, email: data.email, city: data.city, country: data.country, job: data.job })
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
    .then(function () {
      // always executed
    });
    
  }

  handleChange(event) {
	  const state = this.state
	  state[event.target.name] = event.target.value
	  this.setState(state);
  }

  handleSubmit(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/?id=' + this.props.match.params.id,
          data: formData,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
      .then(function (response) {
          //handle success
          console.log(response)
          if(response.status === 200) {
            alert("Contact update successfully.");
          }
      })
      .catch(function (response) {
          //handle error
          console.log(response)
      });
  }

  render() {
    return (
			<div className="container">
        <h1 className="page-header text-center">Update Contact</h1>
			  <Link to="/" className="btn btn-primary btn-xs">Home</Link>
        <div className="col-md-12">
            <div className="panel panel-primary">
                <div className="panel-body">
                <form onSubmit={this.handleSubmit}>
                <input type="hidden" name="id" value={this.state.id}/>
                <label>Name</label>
                <input type="text" name="name" className="form-control" value={this.state.name} onChange={this.handleChange} />
 
                <label>Email</label>
                <input type="email" name="email" className="form-control" value={this.state.email} onChange={this.handleChange} />
 
                <label>Country</label>
                <input type="text" name="country" className="form-control" value={this.state.country} onChange={this.handleChange} />
 
                <label>City</label>
                <input type="text" name="city" className="form-control" value={this.state.city} onChange={this.handleChange} />
 
                <label>Job</label>
                <input type="text" name="job" className="form-control" value={this.state.job} onChange={this.handleChange} />
                <br/>
                <input type="submit" className="btn btn-primary btn-block" value="Update Contact" />
            </form>
                </div>
            </div>
        	</div>
			   </div>
    );
  }
}

export default Update;
src/create.js
//src/create.js
import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class Create extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: '', email:'', city:'', country:'', job:''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
	  const state = this.state
	  state[event.target.name] = event.target.value
	  this.setState(state);
  }
  handleSubmit(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">Add New Contact</h1>
		  	<Link to="/" className="btn btn-primary btn-xs">Home</Link>
			<div className="col-md-12">
            <div className="panel panel-primary">
                <div className="panel-body">
                <form onSubmit={this.handleSubmit}>
                <label>Name</label>
                <input type="text" name="name" className="form-control" value={this.state.name} onChange={this.handleChange} />
 
                <label>Email</label>
                <input type="email" name="email" className="form-control" value={this.state.email} onChange={this.handleChange} />
 
                <label>Country</label>
                <input type="text" name="country" className="form-control" value={this.state.country} onChange={this.handleChange} />
 
                <label>City</label>
                <input type="text" name="city" className="form-control" value={this.state.city} onChange={this.handleChange} />
 
                <label>Job</label>
                <input type="text" name="job" className="form-control" value={this.state.job} onChange={this.handleChange} />
                <br/>
                <input type="submit" className="btn btn-primary btn-block" value="Create Contact" />
            </form>
                </div>
            </div>
        	</div>
		</div>
    );
  }
}

export default Create;
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':
	  if(isset($_GET["id"])){
		$id = $_GET['id'];  
	  }	  	
	  $sql = "select * from contacts".($id?" where id=$id":''); 
      break;
    case 'POST':
		if(isset($_GET["id"])){
			$id = $_GET['id'];  
			$name = $_POST["name"];
			$email = $_POST["email"];
			$country = $_POST["country"];
			$city = $_POST["city"];
			$job = $_POST["job"];
			$sql = "UPDATE contacts SET name='$name', email='$email', city='$city', country='$country', job='$job' WHERE id = $id"; 
		}else if(isset($_GET["delete"])){
			$delete = $_GET['delete'];  
			$sql = "DELETE FROM contacts WHERE id = $delete"; 
		}else{	
		  $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