React + CodeIgniter 4 CRUD + MySQL 8

React js + Codeigniter 4 crud + MySQL tutorial. In this tutorial, i am going to show you how to create React js Codeigniter 4 CRUD application.

In this codeigniter react js crud tutorial, i will create CRUD REST APIs in codeigniter 4 app + MySQL database and consume this CRUD Rest APIs for building react js crud application.

CodeIgniter 4 + React JS CRUD + MySQL 8 Example

  • Step 1: Install Codeigniter 4 Application
  • Step 2: Basic Configurations
  • Step 3: Create Database With Table
  • Step 4: Configure Database With Codeigniter 4 App
  • Step 5: Create Model File
  • Step 6: Create Controller
  • Step 7: Setup React Application
  • Step 8: Create List.js File in React JS App
  • Step 9: Create Create.js File in React JS App
  • Step 10: Create Update.js File in React JS App
  • Step 11: Create Style.css File in React JS App

Step 1: Install Codeigniter 4 Application

Install or download codeigniter 4 application, so go to this link https://codeigniter.com/ and 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

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

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: Configure Database With Codeigniter 4 App

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

Create model; so visit app/Models/ directory and create here one model named ProductModel.php. Then add the following code into your ProductModel.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

Create controller; so visit app/Controllers directory 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

Setup react application. So, You can check the tutorial on how to create new React App.

Step 8: Create List.js File in React JS App

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>
										&nbsp;&nbsp;
										<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 React JS App

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 React JS App

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 React JS App

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

Codeigniter 4 + React js crud + MySQL tutorial.Through this tutorial, you have learned how to create React CRUD example with Codeigniter 4 and MySQL.

Recommende React js + CodeIgniter 4 Tutorial

Leave a Comment