React JS CRUD with CodeIgniter 4 and MySQL 8

In this tutorial, you will learn how to create a CRUD example using React JS, Codeigniter 4 and MySQL. We will guide you step by step on how to use React JS as a front-end technology for building the UI, CodeIgniter 4 web framework for building the REST APIs, and MySQL database as a persistent storage.

CRUD is an important concept in web development, which stands for Create, Read, Update and Delete operations in an application. With this tutorial, you will learn how to perform CRUD operations in React JS using PHP Codeigniter 4 REST APIs. We will create three separate JavaScript files for performing CRUD operations.

Follow this tutorial to build a fully functional CRUD application using React JS, Codeigniter 4, and MySQL. You will learn how to create, read, update and delete data from the database using REST APIs.

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 Latest

To get started, you need to download the latest version of Codeigniter 4. You can download it from this link https://codeigniter.com/download. Once the download is complete, unzip the setup and save it in your local system in the xampp/htdocs/ folder. After that, rename the downloaded folder to “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, we need to create a database with a specific name. To do that, we can open PHPMyAdmin and create a new database by clicking on the “New” button in the left sidebar. Then we can enter the desired name for our database, such as “demo”, and click on the “Create” button to create it.

Once the database is created, we can use SQL queries to create a table within the database. We can use the following SQL query to create a table named “employees” with some basic columns:

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

To connect our project with the database, we need to go to the “app/Config/Database.php” file and open it in a text editor. After opening the file, we need to set up our database credentials in this file, such as the database hostname, username, password, and database name, as shown below. This will establish the connection between our project and the database.

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>
                                        &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 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.

You May Also Like

  1. Send Email in CodeIgniter 4 With SMTP
  2. Codeigniter 4 Resize, Compress Image with Image Manipulation

Leave a Reply

Your email address will not be published. Required fields are marked *