React js crud example with Codeigniter 4 and MySQL tutorial. In this example, you will learn how to create React CRUD example with Codeigniter 4 and MySQL.
This tutorial will show you step by step on how to create React JS as a front-end technology used for building the UI (User Interface), PHP based CodeIgniter 4 web framework will be used to build the REST (Representational State Transfer) APIs and MySQL database will be used as a persistent storage.
And as well as, learn how to build CRUD application using CodeIgniter 4, MySQL and React JS framework. CRUD is an acronym that stands for Create, Read, Update and Delete operations in a particular application. So you are basically creating a record, reading single or all records, updating the existing record and deleting the existing record.
And this tutorial will show you how to perform CRUD operations using php codeigniter 4 REST APIs in React js. And will create three separate JavaScript (js) files for performing CRUD operations.
React JS CRUD Example with CodeIgniter 4 and MySQL 8
Follow the following steps and create react js crud app using php codeigniter 4 and mysql rest apis:
- Step 1: Download Codeigniter Latest
- Step 2: Basic Configurations
- Step 3: Create Database With Table
- Step 4: Setup Database Credentials
- Step 5: Create Model File
- Step 6: Create Controller
- Step 7: Setup React Application
- Step 8: Create List.js File
- Step 9: Create Create.js File
- Step 10: Create Update.js File
- Step 11: Create Style.css File
Step 1: Download Codeigniter Project
In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2: Basic Configurations
Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table
In this step, you need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.
CREATE TABLE `product` ( `id` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT, `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `price` double COLLATE utf8mb4_unicode_ci NOT NULL, `sale_price` double COLLATE utf8mb4_unicode_ci NOT NULL, `sales_count` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL, `sale_date` VARCHAR(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; insert into product(id,name,price,sale_price,sales_count,sale_date) values(1, 'Desktop','30000','35000','55','02-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(2, 'Desktop','30300','37030','43','03-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(3, 'Tablet','39010','48700','145','04-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(4, 'Phone','15000','17505','251','05-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(5, 'Phone','18000','22080','178','05-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(6, 'Tablet','30500','34040','58','05-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(7, 'Adapter','2000','2500','68','06-04-2018'); insert into product(id,name,price,sale_price,sales_count,sale_date) values(8, 'TV','45871','55894','165','07-04-2018');
Step 4: Setup Database Credentials
In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'demo', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];
Step 5: Create Model File
In this step, visit app/Models/ and create here one model named User.php. Then add the following code into your User.php file:
<?php namespace App\Models; use CodeIgniter\Model; class ProductModel extends Model { protected $table = 'product'; protected $primaryKey = 'id'; protected $returnType = 'array'; protected $allowedFields = ['name', 'price', 'sale_price', 'sales_count', 'sale_date']; protected $validationRules = []; protected $validationMessages = []; protected $skipValidation = false; }
Step 6: Create Controller
In this step, Visit app/Controllers and create a controller name Product.php. In this controller, you need to add the following methods into it:
<?php namespace App\Controllers; use CodeIgniter\RESTful\ResourceController; use CodeIgniter\HTTP\RequestInterface; class Product extends ResourceController { protected $modelName = 'App\Models\ProductModel'; protected $format = 'json'; // fetch all products public function index() { return $this->respond($this->model->findAll()); } // save new product info public function create() { // get posted JSON //$json = json_decode(file_get_contents("php://input", true)); $json = $this->request->getJSON(); $name = $json->name; $price = $json->price; $sale_price = $json->sale_price; $sales_count = $json->sales_count; $sale_date = $json->sale_date; $data = array( 'name' => $name, 'price' => $price, 'sale_price' => $sale_price, 'sales_count' => $sales_count, 'sale_date' => $sale_date ); $this->model->insert($data); $response = array( 'status' => 201, 'messages' => array( 'success' => 'Product created successfully' ) ); return $this->respondCreated($response); } // fetch single product public function show($id = null) { $data = $this->model->where('id', $id)->first(); if($data){ return $this->respond($data); }else{ return $this->failNotFound('No product found'); } } // update product by id public function update($id = NULL){ //$json = json_decode(file_get_contents("php://input", true)); $json = $this->request->getJSON(); $price = $json->price; $sale_price = $json->sale_price; $data = array( 'id' => $id, 'price' => $price, 'sale_price' => $sale_price ); $this->model->update($id, $data); $response = array( 'status' => 200, 'messages' => array( 'success' => 'Product updated successfully' ) ); return $this->respond($response); } // delete product by id public function delete($id = NULL){ $data = $this->model->find($id); if($data) { $this->model->delete($id); $response = array( 'status' => 200, 'messages' => array( 'success' => 'Product successfully deleted' ) ); return $this->respondDeleted($response); } else { return $this->failNotFound('No product found'); } } }
Step 7: Setup React Application
In this step, you need to setup react application. So, You can check the tutorial on how to create new React App.
Step 8: Create List.js File
In this step, you need to create list.js file. So visit src/components directory and create list.js and then add the following code into:
import React from 'react'; import { Link } from 'react-router-dom'; class Products extends React.Component { constructor(props) { super(props); this.state = {products: []}; this.headers = [ { key: 'id', label: 'Id'}, { key: 'name', label: 'Name' }, { key: 'price', label: 'Price' }, { key: 'sale_price', label: 'Selling Price' }, { key: 'sales_count', label: 'Sales Count' }, { key: 'sale_date', label: 'Sale Date' } ]; this.deleteProduct = this.deleteProduct.bind(this); } componentDidMount() { fetch('http://localhost:8080/product') .then(response => { return response.json(); }).then(result => { console.log(result); this.setState({ products:result }); }); } deleteProduct(id) { if(window.confirm("Are you sure want to delete?")) { fetch('http://localhost:8080/product/' + id, { method : 'DELETE' }).then(response => { if(response.status === 200) { alert("Product deleted successfully"); fetch('http://localhost:8080/product') .then(response => { return response.json(); }).then(result => { console.log(result); this.setState({ products:result }); }); } }); } } render() { return ( <div id="container"> <Link to="/create">Add Product</Link> <p/> <table> <thead> <tr> { this.headers.map(function(h) { return ( <th key = {h.key}>{h.label}</th> ) }) } <th>Actions</th> </tr> </thead> <tbody> { this.state.products.map(function(item, key) { return ( <tr key = {key}> <td>{item.id}</td> <td>{item.name}</td> <td>{item.price}</td> <td>{item.sale_price}</td> <td>{item.sales_count}</td> <td>{item.sale_date}</td> <td> <Link to={`/update/${item.id}`}>Edit</Link> <a href="javascript:void(0);" onClick={this.deleteProduct.bind(this, item.id)}>Delete</a> </td> </tr> ) }.bind(this)) } </tbody> </table> </div> ) } } export default Products;
Step 9: Create Create.js File
In this step, you need to create create.js file. So visit src/components directory and create create.js and then add the following code into:
import React from 'react'; import { Link } from 'react-router-dom'; class Create extends React.Component { constructor(props) { super(props); this.state = {name: '', price:'', sale_price:'', sales_count:'', sale_date:''}; 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(); fetch('http://localhost:8080/product', { method: 'POST', body: JSON.stringify({ name: this.state.name, price: this.state.price, sale_price: this.state.sale_price, sales_count: this.state.sales_count, sale_date: this.state.sale_date }), headers: { "Content-type": "application/json; charset=UTF-8" } }).then(response => { if(response.status === 201) { alert("New product saved successfully"); } }); } render() { return ( <div id="container"> <Link to="/">Products</Link> <p/> <form onSubmit={this.handleSubmit}> <p> <label>Name:</label> <input type="text" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Name" /> </p> <p> <label>Price:</label> <input type="text" name="price" value={this.state.price} onChange={this.handleChange} placeholder="Price" /> </p> <p> <label>Selling Price:</label> <input type="text" name="sale_price" value={this.state.sale_price} onChange={this.handleChange} placeholder="Selling Price" /> </p> <p> <label>Sales Count:</label> <input type="text" name="sales_count" value={this.state.sales_count} onChange={this.handleChange} placeholder="Sales Count" /> </p> <p> <label>Sale Date:</label> <input type="text" name="sale_date" value={this.state.sale_date} onChange={this.handleChange} placeholder="Sale Date" /> </p> <p> <input type="submit" value="Submit" /> </p> </form> </div> ); } } export default Create;
Step 10: Create Update.js File
In this step, you need to create update.js file. So visit src/components directory and create update.js and then add the following code into:
import React from 'react'; import { Link, withRouter } from 'react-router-dom'; class Update extends React.Component { constructor(props) { super(props); this.state = {id: '', name: '', price:'', sale_price:'', sales_count:'', sale_date:''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } componentDidMount() { fetch('http://localhost:8080/product/' + this.props.match.params.id) .then(response => { return response.json(); }).then(result => { console.log(result); this.setState({ id:result.id, name:result.name, price:result.price, sale_price: result.sale_price, sales_count: result.sales_count, sale_date: result.sale_date }); }); } handleChange(event) { const state = this.state state[event.target.name] = event.target.value this.setState(state); } handleSubmit(event) { event.preventDefault(); //alert(this.props.match.params.id); fetch('http://localhost:8080/product/' + this.props.match.params.id, { method: 'PUT', body: JSON.stringify({ name: this.state.name, price: this.state.price, sale_price: this.state.sale_price, sales_count: this.state.sales_count, sale_date: this.state.sale_date }), headers: { "Content-type": "application/json; charset=UTF-8" } }).then(response => { if(response.status === 200) { alert("Product update successfully."); } }); } render() { return ( <div id="container"> <Link to="/">Products</Link> <p/> <form onSubmit={this.handleSubmit}> <input type="hidden" name="id" value={this.state.id}/> <p> <label>Name:</label> <input type="text" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Name" /> </p> <p> <label>Price:</label> <input type="text" name="price" value={this.state.price} onChange={this.handleChange} placeholder="Price" /> </p> <p> <label>Selling Price:</label> <input type="text" name="sale_price" value={this.state.sale_price} onChange={this.handleChange} placeholder="Selling Price" /> </p> <p> <label>Sales Count:</label> <input type="text" name="sales_count" value={this.state.sales_count} onChange={this.handleChange} placeholder="Sales Count" /> </p> <p> <label>Sale Date:</label> <input type="text" name="sale_date" value={this.state.sale_date} onChange={this.handleChange} placeholder="Sale Date" /> </p> <p> <input type="submit" value="Submit" /> </p> </form> </div> ); } } export default Update;
Step 11: Create Style.css File
In this step, you need to create style.css file. So visit src/ directory and create update.js and then add the following code into:
#container { width: 800px; margin: auto; } table { border-collapse: collapse; width: 800px; margin: 10px auto; } th, td { border: 1px solid #ddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #f2f2f2 } tr:hover { background-color: #ddd; } th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; }
Conclusion
React js crud example with Codeigniter 4 and MySQL tutorial. In this example, you have learned how to create React CRUD example with Codeigniter 4 and MySQL.
If you have any questions or thoughts to share, use the comment form below to reach us.