- React CRUD operations using PHP API and MySQL
- What is NodeJs and NPM?
- What is Homebrew?
- What is PHP?
- What is MySQL?
- What is Apache?
- Stacked Application
- Create Link and Handle Routing in React | react-router-dom package installation
- Create database in PHPMyAdmin and design form in React Component
- Create PHP API and consume using axios | handle CORS issue on localhost
- Connect MySQL database using PDO | Access React form data and Save in Database
- Create GET PHP API and consume in React using axios | List in react table component
- Create DELETE PHP API, consume it using axios and delete user from database
- Saved searches
- Use saved searches to filter your results more quickly
- Aclaputra/react-php-mysql
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
React CRUD operations using PHP API and MySQL
React is a free and open-source front-end JavaScript library for building user interfaces based on UI components. It is maintained by Meta and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications. Here is the official website of ReactJs https://reactjs.org/.
To create react app you’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine.
What is NodeJs and NPM?
Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. You can download from official NodeJs website: https://nodejs.org/en/. NPM will get install along with NodeJs. NPM is the default package manager for the JavaScript runtime environment NodeJs.
What is Homebrew?
For mac you can also use Homebrew to install it on your machine. Homebrew is a free and open-source software package management system that simplifies the installation of software on Apple’s operating system, macOS, as well as Linux. The name is intended to suggest the idea of building software on the Mac depending on the user’s taste. here is the official website https://brew.sh/
Install Homebrew
/bin/bash -c «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)»
Install NodeJs
brew install nodejs
Create ReactJS APP
npx create-react-app react-crud
npx is not a typo — it’s a package runner tool that comes with npm 5.2+.
Create React App doesn’t handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. Under the hood, it uses Babel and webpack, but you don’t need to know anything about them.
Run react app
Now visit to following link you should be able to see ReactApp running:
http://localhost:3000/
To create RestFull API, we’ll be needing PHP, MYSQL and Apache. You are free to install each software separately and configure them or use stacked app. In my case I’m going to use MAMP(Mac Apache MySQL PHP) which is design for mac and comes with all required softwares
What is PHP?
PHP is a open-source general-purpose server side scripting language that is especially suited to web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994. The PHP reference implementation is now produced by The PHP Group.
What is MySQL?
MySQL is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter, and “SQL”, the abbreviation for Structured Query Language.
What is Apache?
The Apache HTTP Server is a free and open-source cross-platform web server software, released under the terms of Apache License 2.0. Apache is developed and maintained by an open community of developers under the auspices of the Apache Software Foundation.
Stacked Application
Awesome now we are all set to start. Open you project to your favourite code editor in my case I’m using Visual Studio Code.
Create Link and Handle Routing in React | react-router-dom package installation
Create new directory components under your src/ directory and create 3 new components which we’ll update shortly:
src/components/ListUser.js
export default function ListUser() < return ( List Users
); >
src/components/CreateUser.js
export default function CreateUser() < return ( Create User
); >
src/components/UpdateUser.js
export default function UpdateUser() < return ( Update User
); >
Now let’s Install react router for creating link and configuring routes
npm install react-router-dom
Update App.js for handling routing
Create database in PHPMyAdmin and design form in React Component
CREATE DTAABASE react_crud;
CREATE TABLE `react_crud`.`users` ( `id` int NOT NULL auto_increment, `name` varchar(50), `email` varchar(60), `mobile` bigint(10), `created_at` timestamp, `updated_at` timestamp, PRIMARY KEY (id) );
Update src/components/CreateUser.js
import < useState >from "react"; export default function ListUser() < const [inputs, setInputs] = useState([]); const handleChange = (event) => < const name = event.target.name; const value = event.target.value; setInputs(values =>()); > const handleSubmit = (event) => < event.preventDefault(); console.log(inputs); >return ( Create user
) >
Create PHP API and consume using axios | handle CORS issue on localhost
Install axios for making API calls from ReactJs
npm install axios
Now update your src/components/CreateUser.js file again for making POST API call
import axios from "axios"; const handleSubmit = (event) => < event.preventDefault(); axios.post('http://localhost:8888/api/user/save', inputs).then(function(response)< console.log(response.data); >); >
Create PHP file for writing API and name it index.php
Notice at the top we have added headers to solved CORS issue.
Also, Let’s create .htaccess file to handle pretty URLs like PHP lumen framework, and add following line inside.
RewriteEngine On RewriteCond % !-d RewriteCond % !-f RewriteRule ^ index.php [L]
Hoola, Finally our API file is ready.
Connect MySQL database using PDO | Access React form data and Save in Database
Now, Let’s create a database connect file and name it DbConnect.php and add following code snippet inside. Update credentials as per yours and it will connect to your database using PDO(PHP Data Object).
server .';dbname=' . $this->dbname, $this->user, $this->pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; > catch (\Exception $e) < echo "Database Error: " . $e->getMessage(); > > > ?>
Create POST API
include("DbConnect.php"); $conn = new DbConnect(); $db = $conn->connect(); $method = $_SERVER['REQUEST_METHOD']; switch($method) < case 'POST': $user = json_decode(file_get_contents('php://input')); $sql = "INSERT INTO users(id, name, email, mobile, created_at) values(null, :name, :email, :mobile, :created_at)"; $stmt = $db->prepare($sql); $date = date('Y-m-d'); $stmt->bindParam(':name', $user->name); $stmt->bindParam(':email', $user->email); $stmt->bindParam(':mobile', $user->mobile); $stmt->bindParam(':created_at', $date); if($stmt->execute()) < $data = ['status' =>1, 'message' => "Record successfully created"]; > else < $data = ['status' =>0, 'message' => "Failed to create record."]; > echo json_encode($data); break; >
// Reference database connection class file and connect to MySQL Database include("DbConnect.php"); $conn = new DbConnect(); $db = $conn->connect();
// Give you Method used to hit API $method = $_SERVER['REQUEST_METHOD'];
// Read the POST JSON data and convert it into PHP Object $user = json_decode(file_get_contents('php://input'));
Create GET PHP API and consume in React using axios | List in react table component
Update src/components/ListUser.js
import axios from "axios" import < useEffect, useState >from "react"; import < Link >from "react-router-dom"; export default function ListUser() < const [users, setUsers] = useState([]); useEffect(() =>< getUsers(); >, []); function getUsers() < axios.get('http://localhost:8888/api/users/').then(function(response) < console.log(response.data); setUsers(response.data); >); > return ( List Users
# Name Email Mobile Actions > /edit`> style=>>Edit )>
) >
Update index.php file for adding new GET API to get all users
case 'GET': $sql = "SELECT * FROM users"; $stmt = $db->prepare($sql); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($users); break;
Load user details for edit form and create PHP PUT API to update user data
Update src/components/UpdateUser.js
import < useState, useEffect >from "react"; import axios from "axios"; import < useNavigate, useParams >from "react-router-dom"; export default function ListUser() < const navigate = useNavigate(); const [inputs, setInputs] = useState([]); const = useParams(); useEffect(() => < getUser(); >, []); function getUser() < axios.get(`http://localhost:8888/api/user/$`).then(function(response) < console.log(response.data); setInputs(response.data); >); > const handleChange = (event) => < const name = event.target.name; const value = event.target.value; setInputs(values =>()); > const handleSubmit = (event) => < event.preventDefault(); axios.put(`http://localhost:8888/api/user/$/edit`, inputs).then(function(response)< console.log(response.data); navigate('/'); >); > return ( Edit user
) >
Update get method to return specific user details by ID
case "GET": $sql = "SELECT * FROM users"; $path = explode('/', $_SERVER['REQUEST_URI']); if(isset($path[3]) && is_numeric($path[3])) < $sql .= " WHERE $stmt = $conn->prepare($sql); $stmt->bindParam(':id', $path[3]); $stmt->execute(); $users = $stmt->fetch(PDO::FETCH_ASSOC); > else < $stmt = $conn->prepare($sql); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); > echo json_encode($users); break;
Now create update API to Handle PUT request
case "PUT": $user = json_decode( file_get_contents('php://input') ); $sql = "UPDATE users SET name= :name, email =:email, mobile =:mobile, updated_at =:updated_at WHERE $stmt = $conn->prepare($sql); $updated_at = date('Y-m-d'); $stmt->bindParam(':id', $user->id); $stmt->bindParam(':name', $user->name); $stmt->bindParam(':email', $user->email); $stmt->bindParam(':mobile', $user->mobile); $stmt->bindParam(':updated_at', $updated_at); if($stmt->execute()) < $response = ['status' =>1, 'message' => 'Record updated successfully.']; > else < $response = ['status' =>0, 'message' => 'Failed to update record.']; > echo json_encode($response); break;
Create DELETE PHP API, consume it using axios and delete user from database
Update src/components/ListUser.js
const deleteUser = (id) => < axios.delete(`http://localhost:8888/api/user/$/delete`).then(function(response)< console.log(response.data); getUsers(); >); >
Update index.php again for writing delete API
case "DELETE": $sql = "DELETE FROM users WHERE $path = explode('/', $_SERVER['REQUEST_URI']); $stmt = $conn->prepare($sql); $stmt->bindParam(':id', $path[3]); if($stmt->execute()) < $response = ['status' =>1, 'message' => 'Record deleted successfully.']; > else < $response = ['status' =>0, 'message' => 'Failed to delete record.']; > echo json_encode($response); break;
Awesome, you have just completed REACT-CRUD using PHP and MySQL, Now run you application and build something beautiful.
Thank you for reading this blog.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
⚗ — Built CRUD React app using Axios with Vanilla PHP Backend REST API to MySQL
Aclaputra/react-php-mysql
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Lets Built CRUD React app with PHP as backend using Axios for REST API to MySQL
If this happen, install Extension access-control-allow-origin
Link extension to unblock access-control-allow-origin -> https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino/related?hl=en-US
Now locate your connections/ambildata.php
Open ./src/axios/Api.js then add your own connections/ambildata.php link
Read data with php as backend from mysql Success.
Create. Update. Delete soon!
Getting Started with Create React App
This project was bootstrapped with Create React App.
In the project directory, you can run:
Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.
The page will reload if you make edits.
You will also see any lint errors in the console.
Launches the test runner in the interactive watch mode.
See the section about running tests for more information.
Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.
Your app is ready to be deployed!
See the section about deployment for more information.
Note: this is a one-way operation. Once you eject , you can’t go back!
If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use eject . The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
To learn React, check out the React documentation.