Codeigniter 4 Ajax Image upload using MySQL

Uploading Images from client to server is one of the most popular features of any web application. jQuery and Ajax can be used to upload images without page refresh. This article explains a simple way to implement the approach to uploading images with Codeigniter 4 Ajax Image upload using jQuery, PHP, and MySQL. This is a very simple example, you can just copy-paste and change according to your requirement.
Before started to implement the Codeigniter 4 Ajax Image upload using MySQL, look files structure:
  • codeigniter-ajax-image-upload-using-mysql
    • app
      • Config
        • App.php
        • Constants.php
        • Database.php
        • Routes.php
      • Controllers
        • Gallery.php
      • Models
        • GalleryModel.php
      • Views
        • user
          • index.php
        • templates
          • header.php
          • footer.php
          • menus.php
    • public
      • .htaccess
      • index.php
    • .htaccess
    • .env
    • assets
      • images
      • uploads
      • css
        • style.css
        • sticky-footer-navbar.css
Step 1 – Install Codeigniter 4 Application
To handle the actual install you would use the following command in your terminal or visit Codeigniter site and download the Codeigniter application.
Display Errors
You may turn on the feature to errors, go to the app/Config/Boot/production.php and change display_errors prop value to 1 from 0.
Step 2 – Basic App Configurations
Now, you need to some basic configuration on the app/config/app.php file.
Step 3: Create the Database and Table
For this tutorial, you need a MySQL database with the following table:
Step 4: Setup and Configure Database access
Update the file app/Config/Database.php OR .env file:
i) .env
ii) Database.php
Step 4: Create and Update User Model
Create a model file named UserModel.php inside “app/Models” folder.
Step 5: Create controllers
Create a controllers file named User.php inside “app/Controllers” folder.
Add/Update code the file app/Config/Routes.php in your CodeIgniter installation with you controller’s name.
Step 6: Create views
Create a views file named index.php inside “add/Views/gallery” folder.
Step 7: Create ajax
Now in app.js, we will handle functionality to upload image Ajax request, inside “assets/js” folder.
Create files named (header.php, menus.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
i) header.php
ii) menus.php
iii) footer.php