article

Saturday, November 6, 2021

ReactJS Fetch Data from Database with PHP Mysql

ReactJS Fetch Data from Database with PHP Mysql

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/

Database Table

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545);

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

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

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')
)
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/App.js
//src/App.js
import React from 'react';

class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = {employee: []};
		this.headers = [
			{ key: 'id', label: 'Id'},
			{ key: 'name', label: 'Name' },
			{ key: 'position', label: 'Position' },
			{ key: 'office', label: 'Office' },
			{ key: 'age', label: 'Age' },
			{ key: 'salary', label: 'Salary' }
		];
		this.state = { checkedBoxes: []	};
		this.deleteEmployee = this.deleteEmployees.bind(this);
		this.toggleCheckbox = this.toggleCheckbox.bind(this);
	}
	
	deleteEmployees = (event) => {
		event.preventDefault();
		if(window.confirm('Are you sure, want to delete the selected employee?')) {
			alert(this.state.checkedBoxes + " Succesfully Deleted");
		}
	}
	
	toggleCheckbox = (e, item) => {		
		if(e.target.checked) {
			let arr = this.state.checkedBoxes;
			arr.push(item.id);
			
			this.setState = { checkedBoxes: arr};
		} else {			
			let items = this.state.checkedBoxes.splice(this.state.checkedBoxes.indexOf(item.id), 1);
			
			this.setState = {
				checkedBoxes: items
			}
		}		
		console.log(this.state.checkedBoxes);
	}
	
	componentDidMount() {
		fetch('http://localhost/devtest/reactjs/employee.php/').then(response => {
			console.log(response);
			return response.json();
		  }).then(result => {
			// Work with JSON data here
			console.log(result);
			this.setState({
				employee_rs:result
			});	
		  }).catch(err => {
			// Do something for an error here
			console.log("Error Reading data " + err);
		  });
	}
		
	render() {
		const employeeFound = this.state.employee_rs && this.state.employee_rs.length;
		if(employeeFound) {
			return (
				<div className="container"><h1>ReactJS Fetch Data from Database with PHP Mysql</h1>
					<div id="msg"></div>
					<button type="button" className="btn btn-danger" onClick={this.deleteEmployees}>Delete Selected Employee(s)</button>
					<table className="table table-bordered table-striped">
						<thead>
							<tr>
								{
									this.headers.map(function(h) {
										return (
											<th key={h.key}>{h.label}</th>
										)
									})
								}
							</tr>
						</thead>
						<tbody>
							{
								this.state.employee_rs.map(function(item, index) {
								return (
									<tr key={index}>
									  <td><input type="checkbox" className="selectsingle" value="{item.id}" checked={this.state.checkedBoxes.find((p) => p.id === item.id)} onChange={(e) => this.toggleCheckbox(e, item)}/>
									    {item.id}
									  </td>
									  <td>{item.name}</td>
									  <td>{item.position}</td>
									  <td>{item.office}</td>
									  <td>{item.age}</td>
									  <td>{item.salary}</td>
									</tr>
								)}.bind(this))
							}
						</tbody>
					</table>
				</div>
			)
		} else {
			return (
				<div id="container">
					No product found
				</div>
			)
		}
	}
}
export default App;
http://localhost/devtest/reactjs/employee.php
//http://localhost/devtest/reactjs/employee.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 employee"; 
      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 ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();

Related Post