Codeigniter For Validation With Error Message Example

Hi Guys

In this tutorial,i will show you how to implement server side validation example,it can easyli Codeigniter Server Side Form Validation With Error Message in this example,normal validation two sides like server side and client side, i will give you simple example of form validation in codeigniter application. we will use form_validation library for add form validation with error message display in codeigniter.

we can use defaulut following validation rules of codeigniter.We can use default following validation rules of codeigniter

  • required
  • regex_match
  • matches
  • differs
  • is_unique
  • min_length
  • max_length
  • exact_length
  • greater_than
  • You can see more from here
Codeigniter Validation Rules. Exmaple

So here i gave you full example of form validation in codeigniter application. i created simple form with first name, last name, email and Mobile Number like contact us form and i set server side validation.

Step:1 Download Codeigniter Project

Here in this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ . And change the download folder name "demo"

Step:2 Basic Configurations

Here in this step,we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';
Step:3 Create Database With Table

Here in this step,we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo. you can use the below sql query for creating a table in your database.

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    first_name varchar(100) NOT NULL COMMENT 'Name',
    last_name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
Step:4 Setup Database Credentials

Here in this step,we need in this step connect our project to database. go to the application/config/ and open database.php file in text editor.We need to setup database credential in this file like below.

$db['default'] = array(
  'dsn' => '',
  'hostname' => 'localhost',
  'username' => 'root',
  'password' => '',
  'database' => 'demo',
  'dbdriver' => 'mysqli',
  'dbprefix' => '',
  'pconnect' => FALSE,
  'db_debug' => (ENVIRONMENT !== 'production'),
  'cache_on' => FALSE,
  'cachedir' => '',
  'char_set' => 'utf8',
  'dbcollat' => 'utf8_general_ci',
  'swap_pre' => '',
  'encrypt' => FALSE,
  'compress' => FALSE,
  'stricton' => FALSE,
  'failover' => array(),
  'save_queries' => TRUE
);
Step:5 Create Controller

Here in this step,we create a controller name Users.php. In this controller we will create some method/function. We will build some of the methods like :

-> Index() – This is used to display a form.

-> post_validate() – This is used to validate data on server side and store a data into database.

<?php
class Users extends CI_Controller {
  
    public function __construct()
    {
        parent::__construct();
        $this->load->library(array('form_validation','session'));
        $this->load->helper(array('url','html','form'));
        $this->load->database();
    }
  
    public function index()
    {
      $this->load->view('form_validation');
    }
    public function post_validate()
    {
 
        $this->form_validation->set_rules('first_name', 'First Name', 'required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'required');
        $this->form_validation->set_rules('contact_no', 'Contact No', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');
 
        $this->form_validation->set_error_delimiters('<div class="error">','</div>');
        $this->form_validation->set_message('required', 'Enter %s');
 
        if ($this->form_validation->run() === FALSE)
        {  
            $this->load->view('form_validation');
        }
        else
        {   
          $data = array(
             'first_name' => $this->input->post('first_name'),
             'last_name' => $this->input->post('last_name'),
             'contact_no' => $this->input->post('contact_no'),
             'email' => $this->input->post('email'),
 
           );
   
            $insert = $this->db->insert('users', $data);
            if ($insert) {
               $this->load->view('success');
            } else {
               redirect( base_url('users') ); 
            }
   
            }
 
    }
 
}
Step:6 Create Views

Now in this step we will create a form_validation.php , go to application/views/ folder and create form_validation.php file. Here put the below html code for showing form.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Form Validation - nicesnippets.com </title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
 <div class="container">
    <br>
    <div class="row">
    <div class="col-md-9">
    <form action="<?php echo base_url('users/post_validate') ?>" method="post" accept-charset="utf-8">
      <div class="form-group">
        <label for="formGroupExampleInput">First Name</label>
        <input type="text" name="first_name" class="form-control" id="formGroupExampleInput" placeholder="Please enter first name">
        <?php echo form_error('first_name'); ?> 
      </div> 
 
      <div class="form-group">
        <label for="formGroupExampleInput">Last Name</label>
        <input type="text" name="last_name" class="form-control" id="formGroupExampleInput" placeholder="Please enter last name">
        <?php echo form_error('last_name'); ?>  
      </div>
 
      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
        <?php echo form_error('email'); ?> 
      </div>   
 
      <div class="form-group">
        <label for="mobile_number">Mobile Number</label>
        <input type="text" name="contact_no" class="form-control" id="contact_no" placeholder="Please enter mobile number" maxlength="10">
        <?php echo form_error('contact_no'); ?> 
      </div>
 
      <div class="form-group">
       <button type="submit" id="send_form" class="btn btn-success">Submit</button>
      </div>
    </form>
    </div>
    <div class="col-md-3">
      <?php $this->load->view('layout/media_left_side_bar'); ?>
    </div>
    </div>
</div>
</body>
</html>
Step:7 Success Views

Now in this step we need to create success.php file, so go to application/views/ and create success.php file. And put the below code here.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Form Validation - nicesnippets.com </title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
 <h1> Thank You for Registered</h1>
</div>
</body>
</html>
Start Server And Run Program

For start development server, Go to the browser and hit below the url.

http://localhost/demo/users

I hope it can help you...

PHP Ajax Image Upload With Preview Example

Hi Guys,

In this tutorial, i will give you simple example of ajax image upload with preview in php. Uploading image via an jquery AJAX in php. I have added code for doing PHP image upload with AJAX without reloading the page.

xI use jQuery AJAX to implement image upload. There is a form with file input field and a submit button. On submitting the form with the selected image file, the AJAX script will be executed. In this code, it sends the upload request to PHP with the uploaded image. PHP code moves the uploaded image to the target folder and returns the image HTML to show the preview as an AJAX response.

The following code shows the HTML for the image upload form. On submitting this form the AJAX function will be called to send the request to the PHP image upload code.

Create Form form.php
<html>
<head>
   <title>PHP AJAX Image Upload</title>
   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">
</head>
<body>
<div class="container">
   <div class="col-md-6 offset-md-3">
      <div class="card">
         <div class="card-title p-1 bg-success">
            <h6>PHP AJAX Image Upload</h6>
         </div>
         <div class="card-body">
            <form id="uploadForm" action="upload.php" method="post">
               <div class="col-md-12 bg-light mb-2 text-center">
                  <div id="targetLayer">No Image</div>
               </div>
               <div class="form-group">
                  <input name="userImage" type="file" class="form-controller" />
               </div>
               <input type="submit" value="Submit" class="btn btn-success" />
            </form>
         </div>
      </div>
   </div>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function (e) {
   $("#uploadForm").on('submit',(function(e) {
      e.preventDefault();
      $.ajax({
           url: "upload.php",
         type: "POST",
         data:  new FormData(this),
         contentType: false,
         cache: false,
         processData:false,
         success: function(data)
          {
            $("#targetLayer").html(data);
          },
              error: function() 
          {
          }            
      });
	}));
});
</script>
</html>
Create Upload Fille upload.php
<?php
  if(is_array($_FILES)) {
    if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
      $sourcePath = $_FILES['userImage']['tmp_name'];
      $targetPath = "images/".$_FILES['userImage']['name'];
      if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img class="img-fluid" width="100%" height="100" src="<?php echo $targetPath; ?>" />
<?php
  }
    }
      }
?>

it code is a redy php ajax image upload with preview and the run code.

it will help you..