Wednesday, January 18

How to upload images using Codeigniter 3 and save them into MySQL database

codeigniter-image-upload

Image upload is the most important chapter in Web Development. I am creating Web applications from last 3 years using codeigniter and one of the most frequently used codes in my projects is uploading images and save them into the database.So today I will show you how to upload images using codeigniter 3 and save them on the database.

Lets discuss about the steps to upload images using codeigniter 3 and save them on the database. The process is very simple.First we upload the image in a folder associated with the project and then we save the url of uploaded image on the database.It is as simple as bellow :

  Step I - Download Codeigniter 3: You can download Codeigniter 3  from their official website - https://www.codeigniter.com/download .You can also Download Github repository of Codeigniter 3  - https://github.com/bcit-ci/CodeIgniter .

  Step II - Create Views: First Setup the codeigniter base_url() function and then go to application>>views folder. In views folder of codeigniter 3 you can see the file - welcome_message.php , edit this file and Create an Image Upload form.You can also copy and pest the bellow code to create Image upload form.
<html>
<head>
  <title>Upload Image Form</title>
</head>
<body>
<?php echo form_open_multipart('Welcome/image_upload/' , array('id' => 'img'));?>
  <h3>Image Upload Form</h3>
  <input type="file" name="pic" tabindex="2" required>
  <input type="text" name="alt" placeholder="Image Alt Text" tabindex="1" required>
  <button type="submit" id="img-submit" data-submit="Sending">Submit</button>
</form>
</body>
</html>
   
You can also add some CSS codes to Design the form.
  Step III - Create Database and Image Upload Folder: Now create a folder in your project  where images will be uploaded and create a table - 'image_upload' in your project database from phpmyadmin, you can also copy and pest the bellow code to create a table :
CREATE TABLE `image_upload` (
`image_url` VARCHAR( 50 ) NOT NULL ,
`alt` VARCHAR( 50 ) NOT NULL 
) ENGINE = MYISAM ;

  Step IV - Controller: Now go to application>>Controller , there will be a php file names 'Welcome.php'. First you need to add form and url helper and load the database like bellow:
public function __construct()
{
  parent::__construct();
  $this->load->database();
  $this->load->helper('url');
  $this->load->helper('form');
}

Now create an image upload function in your Controller as bellow:
function do_upload()
{
  $url = "../images";
  $image=basename($_FILES['pic']['name']);
  $image=str_replace(' ','|',$image);
  $type = explode(".",$image);
  $type = $type[count($type)-1];
  if (in_array($type,array('jpg','jpeg','png','gif')))
  {
    $tmppath="images/".uniqid(rand()).".".$type; // uniqid(rand()) function generates unique random number.
    if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
    {
      move_uploaded_file($_FILES['pic']['tmp_name'],$tmppath);
      return $tmppath; // returns the url of uploaded image.
    }
  }
  else
  {
    redirect(base_url() . 'index.php/Welcome/not_img', 'refresh');// redirect to show file type not support message
  }
}

The function 'do_upload' is uploading the selected image from the form of welcome_message.php into the folder you have created in Step-III and returns the image url.
Now we will save the url of uploaded image into MySQL database.See the bellow code:
function image_upload()
{
  $data ['image_url']= $this->do_upload();
  $data ['alt']= $this->input->post('alt');
  $this->db->insert('image_upload', $data);
  redirect(base_url() . 'index.php/Welcome/', 'refresh');// Redirect to Success page
}

The function 'image_upload' will save the image url on your database.You can view the uploaded images by using bellow code:
<?php
  $images = $this->db->get('image_upload')->result_array();
  foreach($images as $row):
?>
  <img src="<?php echo base_url().$row['image_url'];?>" class="img" alt="" />
<?
  endforeach;
?>
So this are the simple steps to upload image using Codeigniter 3 and save in MySQL database.Thanks for reading this. If you fill any problem regarding this example of code you can say that in comment section.