Categories: Snippets

Sample Contact Form with validation, Captcha & Notification

Contact Controller

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Contact extends Public_Controller {

    /**
     * Constructor
     */    function __construct()
    {
        parent::__construct();

        // load the model file
        $this->load->model('contact_model');
        $this->load->model('notifications_model');

        // load the captcha helper
        $this->load->helper('captcha');
    }


    /**************************************************************************************
     * PUBLIC FUNCTIONS
     **************************************************************************************/

    /**
     * Default
     */    public function index()
    {
        // validators
        $this->form_validation->set_error_delimiters($this->config->item('error_delimeter_left'), $this->config->item('error_delimeter_right'));
        $this->form_validation->set_rules('name', lang('contacts_name'), 'required|trim|max_length[64]');
        $this->form_validation->set_rules('email', lang('contacts_email'), 'required|trim|valid_email|min_length[10]|max_length[256]');
        $this->form_validation->set_rules('title', lang('common_title'), 'required|trim|max_length[128]');
        $this->form_validation->set_rules('message', lang('contacts_message'), 'required|trim|min_length[10]');
        $this->form_validation->set_rules('captcha', lang('contacts_captcha'), 'required|trim|callback__check_captcha');

        if ($this->form_validation->run() == TRUE)
        {
            // attempt to save and send the message
            $post_data = $this->security->xss_clean($this->input->post());
            $saved_and_sent = $this->contact_model->save_and_send_message($post_data, $this->settings);

            if ($saved_and_sent)
            {
                $notification   = array(
                    'users_id'  => 1,
                    'n_type'    => 'contacts',
                    'n_content' => 'noti_new_message',
                    'n_url'     => site_url('admin/contacts'),
                );
                $this->notifications_model->save_notifications($notification);

                // redirect to home page
                $this->session->set_flashdata('message', sprintf(lang('contacts_send_success'), $this->input->post('name', TRUE)));
                redirect(site_url('contact'));
            }
            else
            {
                // stay on contact page
                $this->error = sprintf(lang('contacts_error_send_failed'), $this->input->post('name', TRUE));
            }
        }

        // create captcha image
        $captcha = create_captcha(array(
            'img_path'   => "./captcha/",
            'img_url'    => base_url('/captcha') . "/",
            'font_path'  => FCPATH . "themes/core/fonts/bromine/Bromine.ttf",
            'img_width'  => 300,
            'img_height' => 100
        ));

        $captcha_data = array(
            'captcha_time' => $captcha['time'],
            'ip_address'   => $this->input->ip_address(),
            'word'        => $captcha['word']
        );

        // store captcha image
        $this->contact_model->save_captcha($captcha_data);

        // setup page header data
        $this
        ->add_js_theme( "pages/contact/index.js")
        ->set_title( lang('menu_contact') );

        $data = $this->includes;

        // set content data
        $content_data = array(
            'captcha_image' => $captcha['image']
        );

        // load views
        $data['content'] = $this->load->view('contact_form', $content_data, TRUE);
        $this->load->view($this->template, $data);
    }


    /**************************************************************************************
     * PRIVATE VALIDATION CALLBACK FUNCTIONS
     **************************************************************************************/

    /**
     * Verifies correct CAPTCHA value
     *
     * @param  string $captcha
     * @return string|boolean
     */    function _check_captcha($captcha)
    {
        $verified = $this->contact_model->verify_captcha($captcha);

        if ($verified == FALSE)
        {
            $this->form_validation->set_message('_check_captcha', lang('contacts_error_captcha'));
            return FALSE;
        }
        else
        {
            return $captcha;
        }
    }

}

Contact_form.php – view

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<!-- Section -->
<section class="bg-lgrey">  
    <div class="container">
        <div class="row">
            <div class="col-sm-offset-1 col-sm-4">
                <!-- Title -->
                <div class="title-container sm text-left">
                    <div class="title-wrap">
                        <h5 class="title"><?php echo lang('menu_contact') ?></h5>
                        <span class="separator line-separator"></span>
                    </div>
                </div><!-- Title -->
                <div class="contact-info">
                    <div class="info-icon bg-dark">
                        <i class="uni-map2"></i>
                    </div>
                    <h5 class="title"><?php echo lang('contacts_office') ?></h5>
                    <p><?php echo $this->settings->institute_name ?></p>
                    <p><?php echo $this->settings->institute_address ?></p>
                </div><!-- Contact Info -->
                
                <div class="contact-info margin-top-30">
                    <div class="info-icon bg-dark">
                        <i class="uni-mail"></i>
                    </div>
                    <h5 class="title"><?php echo lang('menu_contact') ?></h5>
                    <p><a href="mailto:<?php echo $this->settings->site_email ?>"><?php echo $this->settings->site_email ?></a></p>
                    <p><a href="tel:<?php echo $this->settings->institute_phone ?>"><?php echo $this->settings->institute_phone ?></a></p>
                </div><!-- Contact Info -->
                
            </div><!-- Column -->
            
            <div class="col-sm-6">
                <!-- Title -->
                <div class="title-container sm text-left">
                    <div class="title-wrap">
                        <h5 class="title"><?php echo lang('contacts_get_in_touch') ?></h5>
                        <span class="separator line-separator"></span>
                    </div>
                </div><!-- Title -->
                <div class="contact-info">
                    <div class="info-icon bg-dark">
                        <i class="uni-fountain-pen"></i>
                    </div>
                    <?php echo form_open('', array('role'=>'form', 'id'=>'form-create')); ?>
                    <div class="input-text form-group<?php echo form_error('name') ? ' has-error' : ''; ?>">
                        <?php echo form_label(lang('contacts_name'), 'name', array('class'=>'control-label')); ?>
                        <span class="required">*</span>
                        <?php echo form_input(array('name'=>'name', 'value'=>set_value('name'), 'class'=>'form-control input-name')); ?>
                    </div>
                    <div class="input-email form-group <?php echo form_error('email') ? ' has-error' : ''; ?>">
                        <?php echo form_label(lang('contacts_email'), 'email', array('class'=>'control-label')); ?>
                        <span class="required">*</span>
                        <?php echo form_input(array('name'=>'email', 'value'=>set_value('email'), 'class'=>'form-control input-email')); ?>
                    </div>
                    <div class="input-text form-group <?php echo form_error('title') ? ' has-error' : ''; ?>">
                        <?php echo form_label(lang('common_title'), 'title', array('class'=>'control-label')); ?>
                        <span class="required">*</span>
                        <?php echo form_input(array('name'=>'title', 'value'=>set_value('title'), 'class'=>'form-control input-text ')); ?>
                    </div>
                    <div class="textarea-message form-group <?php echo form_error('message') ? ' has-error' : ''; ?>">
                        <?php echo form_label(lang('contacts_message'), 'message', array('class'=>'control-label')); ?>
                        <span class="required">*</span>
                        <?php echo form_textarea(array('name'=>'message', 'value'=>set_value('message'), 'class'=>'form-control textarea-message')); ?>
                    </div>
                    <div class="form-group textarea-message <?php echo form_error('captcha') ? ' has-error' : ''; ?>">
                        <?php echo form_label(lang('contacts_captcha'), 'captcha', array('class'=>'control-label')); ?>
                        <br />
                        <?php echo $captcha_image; ?>
                        <?php echo form_input(array('name'=>'captcha', 'id'=>'captcha', 'value'=>"", 'class'=>'form-control textarea-message')); ?>
                    </div>
                    <button type="submit" name="submit" class="btn"><i class="fa fa-send"></i> <?php echo lang('contacts_send_message') ?></button>
                    <span id="submit-loader"></span>
                    <?php echo form_close(); ?>
                </div><!-- Contact Info -->
            </div><!-- Column -->
        </div><!-- Row -->
    </div><!-- Container -->    
</section><!-- Section -->  

Contact_model

<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Contact Model
 *
 * This model handles contacts module data
 *

*/
class Contact_model extends CI_Model {

    /**
     * @vars
     */    private $_db;


    /**
     * Constructor
     */    function __construct()
    {
        parent::__construct();

        // define primary table
        $this->_db = 'emails';
    }


    /**
     * Save generated CAPTCHA to database
     *
     * @param  array $data
     * @return boolean
     */    public function save_captcha($data = array())
    {
        // CAPTCHA data required
        if ($data)
        {
            // insert CAPTCHA
            $query = $this->db->insert_string('captcha', $data);
            $this->db->query($query);

            // return
            return TRUE;
        }

        return FALSE;
    }


    /**
     * Verify CAPTCHA
     *
     * @param  string $captcha
     * @return boolean
     */    public function verify_captcha($captcha = NULL)
    {
        // CAPTCHA string required
        if ($captcha)
        {
            // remove old CAPTCHA
            $expiration = time() - 7200; // 2-hour limit
            $this->db->query("DELETE FROM captcha WHERE captcha_time < {$expiration}");

            // build query
            $sql = "
                SELECT
                    COUNT(*) AS count
                FROM captcha
                WHERE word = " . $this->db->escape($captcha) . "
                    AND ip_address = '" . $this->input->ip_address() . "'
                    AND captcha_time > '{$expiration}'
            ";

            // execute query
            $query = $this->db->query($sql);

            // return results
            if ($query->row()->count > 0)
            {
                return TRUE;
            }
        }

        return FALSE;
    }


    /**
     * Save and email contact message
     *
     * @param  array $data
     * @param  array $settings
     * @return boolean
     */    public function save_and_send_message($data=array(), $settings=array())
    {
        // post data and settings required
        if ($data && $settings)
        {
            // build query
            $sql = "
                INSERT INTO {$this->_db} (
                    name, email, title, message, created
                ) VALUES (
                    " . $this->db->escape($data['name']) . ",
                    " . $this->db->escape($data['email']) . ",
                    " . $this->db->escape($data['title']) . ",
                    " . $this->db->escape($data['message']) . ",
                    '" . date('Y-m-d H:i:s') . "'
                )
            ";

            // execute query
            $this->db->query($sql);

            if ($id = $this->db->insert_id() && $_SERVER['HTTP_HOST'] !== 'localhost')
            {
                try
                {
                    // send email
                    $this->email->from($data['email'], $data['name']);
                    $this->email->to($settings->site_email);
                    $this->email->subject($data['title']);
                    $this->email->message($data['message']);
                    $send_mail = @$this->email->send();
                    #echo $this->email->print_debugger();

                    if ($send_mail)
                    {
                        return TRUE;
                    }
                    else
                    {
                        // send mail failed - remove message from database
                        $this->db->query("DELETE FROM {$this->_db} WHERE id = {$id}");
                    }
                }
                catch (Exception $e)
                {
                    // send mail failed - remove message from database
                    $this->db->query("DELETE FROM {$this->_db} WHERE id = {$id}");
                }
            }
            else
            {
                return TRUE;
            }
        }

        return FALSE;
    }


    /**
     * Get list of non-deleted users
     *
     * @param  int $limit
     * @param  int $offset
     * @param  array $filters
     * @param  string $sort
     * @param  string $dir
     * @return array|boolean
     */    function get_all($limit = 0, $offset = 0, $filters = array(), $sort = 'created', $dir = 'DESC')
    {
        // start building query
        $sql = "
            SELECT SQL_CALC_FOUND_ROWS *
            FROM {$this->_db}
            WHERE 1 = 1
        ";

        // apply filters
        if ( ! empty($filters))
        {
            foreach ($filters as $key=>$value)
            {
                $value = $this->db->escape('%' . $value . '%');
                $sql .= " AND {$key} LIKE {$value}";
            }
        }

        // continue building query
        $sql .= " ORDER BY {$sort} {$dir}";

        // add limit and offset
        if ($limit)
        {
            $sql .= " LIMIT {$offset}, {$limit}";
        }

        // execute query
        $query = $this->db->query($sql);

        // define results
        if ($query->num_rows() > 0)
        {
            $results['results'] = $query->result_array();
        }
        else
        {
            $results['results'] = NULL;
        }

        // get total count
        $sql = "SELECT FOUND_ROWS() AS total";
        $query = $this->db->query($sql);
        $results['total'] = $query->row()->total;

        // return results
        return $results;
    }


    /**
     * Set email message as read
     *
     * @param  int $id
     * @param  int $read_by
     * @return boolean
     */    public function read($id = NULL, $read_by = NULL)
    {
        // data required
        if ($id and $read_by)
        {
            // build query string
            $sql = "
                UPDATE {$this->_db}
                SET `read` = '" . date('Y-m-d H:i:s') . "',
                    read_by = {$read_by}
                WHERE id = {$id}
            ";

            // execute query
            $this->db->query($sql);

           // return results
            if ($this->db->affected_rows())
            {
                return TRUE;
            }
        }

        return FALSE;
    }

}

/*Contact model ends*/

Captcha Helper

<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014 - 2018, British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package CodeIgniter
 * @author EllisLab Dev Team
 * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
 * @copyright Copyright (c) 2014 - 2018, British Columbia Institute of Technology (http://bcit.ca/)
 * @license http://opensource.org/licenses/MIT MIT License
 * @link https://codeigniter.com
 * @since Version 1.0.0
 * @filesource
 */defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CodeIgniter CAPTCHA Helper
 *
 * @package  CodeIgniter
 * @subpackage Helpers
 * @category Helpers
 * @author  EllisLab Dev Team
 * @link  https://codeigniter.com/user_guide/helpers/captcha_helper.html
 */
// ------------------------------------------------------------------------

if ( ! function_exists('create_captcha'))
{
 /**
  * Create CAPTCHA
  *
  * @param array $data  Data for the CAPTCHA
  * @param string $img_path Path to create the image in (deprecated)
  * @param string $img_url URL to the CAPTCHA image folder (deprecated)
  * @param string $font_path Server path to font (deprecated)
  * @return string
  */ function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
 {
  $defaults = array(
   'word'  => '',
   'img_path' => '',
   'img_url' => '',
   'img_width' => '150',
   'img_height' => '30',
   'font_path' => '',
   'expiration' => 7200,
   'word_length' => 8,
   'font_size' => 16,
   'img_id' => '',
   'pool'  => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
   'colors' => array(
    'background' => array(255,255,255),
    'border' => array(153,102,102),
    'text'  => array(204,153,153),
    'grid'  => array(255,182,182)
   )
  );

  foreach ($defaults as $key => $val)
  {
   if ( ! is_array($data) && empty($$key))
   {
    $$key = $val;
   }
   else
   {
    $$key = isset($data[$key]) ? $data[$key] : $val;
   }
  }

  if ($img_path === '' OR $img_url === ''
   OR ! is_dir($img_path) OR ! is_really_writable($img_path)
   OR ! extension_loaded('gd'))
  {
   return FALSE;
  }

  // -----------------------------------
  // Remove old images
  // -----------------------------------

  $now = microtime(TRUE);

  $current_dir = @opendir($img_path);
  while ($filename = @readdir($current_dir))
  {
   if (in_array(substr($filename, -4), array('.jpg', '.png'))
    && (str_replace(array('.jpg', '.png'), '', $filename) + $expiration) < $now)
   {
    @unlink($img_path.$filename);
   }
  }

  @closedir($current_dir);

  // -----------------------------------
  // Do we have a "word" yet?
  // -----------------------------------

  if (empty($word))
  {
   $word = '';
   $pool_length = strlen($pool);
   $rand_max = $pool_length - 1;

   // PHP7 or a suitable polyfill
   if (function_exists('random_int'))
   {
    try
    {
     for ($i = 0; $i < $word_length; $i++)
     {
      $word .= $pool[random_int(0, $rand_max)];
     }
    }
    catch (Exception $e)
    {
     // This means fallback to the next possible
     // alternative to random_int()
     $word = '';
    }
   }
  }

  if (empty($word))
  {
   // Nobody will have a larger character pool than
   // 256 characters, but let's handle it just in case ...
   //
   // No, I do not care that the fallback to mt_rand() can
   // handle it; if you trigger this, you're very obviously
   // trying to break it. -- Narf
   if ($pool_length > 256)
   {
    return FALSE;
   }

   // We'll try using the operating system's PRNG first,
   // which we can access through CI_Security::get_random_bytes()
   $security = get_instance()->security;

   // To avoid numerous get_random_bytes() calls, we'll
   // just try fetching as much bytes as we need at once.
   if (($bytes = $security->get_random_bytes($pool_length)) !== FALSE)
   {
    $byte_index = $word_index = 0;
    while ($word_index < $word_length)
    {
     // Do we have more random data to use?
     // It could be exhausted by previous iterations
     // ignoring bytes higher than $rand_max.
     if ($byte_index === $pool_length)
     {
      // No failures should be possible if the
      // first get_random_bytes() call didn't
      // return FALSE, but still ...
      for ($i = 0; $i < 5; $i++)
      {
       if (($bytes = $security->get_random_bytes($pool_length)) === FALSE)
       {
        continue;
       }

       $byte_index = 0;
       break;
      }

      if ($bytes === FALSE)
      {
       // Sadly, this means fallback to mt_rand()
       $word = '';
       break;
      }
     }

     list(, $rand_index) = unpack('C', $bytes[$byte_index++]);
     if ($rand_index > $rand_max)
     {
      continue;
     }

     $word .= $pool[$rand_index];
     $word_index++;
    }
   }
  }

  if (empty($word))
  {
   for ($i = 0; $i < $word_length; $i++)
   {
    $word .= $pool[mt_rand(0, $rand_max)];
   }
  }
  elseif ( ! is_string($word))
  {
   $word = (string) $word;
  }

  // -----------------------------------
  // Determine angle and position
  // -----------------------------------
  $length = strlen($word);
  $angle = ($length >= 6) ? mt_rand(-($length-6), ($length-6)) : 0;
  $x_axis = mt_rand(6, (360/$length)-16);
  $y_axis = ($angle >= 0) ? mt_rand($img_height, $img_width) : mt_rand(6, $img_height);

  // Create image
  // PHP.net recommends imagecreatetruecolor(), but it isn't always available
  $im = function_exists('imagecreatetruecolor')
   ? imagecreatetruecolor($img_width, $img_height)
   : imagecreate($img_width, $img_height);

  // -----------------------------------
  //  Assign colors
  // ----------------------------------

  is_array($colors) OR $colors = $defaults['colors'];

  foreach (array_keys($defaults['colors']) as $key)
  {
   // Check for a possible missing value
   is_array($colors[$key]) OR $colors[$key] = $defaults['colors'][$key];
   $colors[$key] = imagecolorallocate($im, $colors[$key][0], $colors[$key][1], $colors[$key][2]);
  }

  // Create the rectangle
  ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $colors['background']);

  // -----------------------------------
  //  Create the spiral pattern
  // -----------------------------------
  $theta  = 1;
  $thetac  = 7;
  $radius  = 16;
  $circles = 20;
  $points  = 32;

  for ($i = 0, $cp = ($circles * $points) - 1; $i < $cp; $i++)
  {
   $theta += $thetac;
   $rad = $radius * ($i / $points);
   $x = ($rad * cos($theta)) + $x_axis;
   $y = ($rad * sin($theta)) + $y_axis;
   $theta += $thetac;
   $rad1 = $radius * (($i + 1) / $points);
   $x1 = ($rad1 * cos($theta)) + $x_axis;
   $y1 = ($rad1 * sin($theta)) + $y_axis;
   imageline($im, $x, $y, $x1, $y1, $colors['grid']);
   $theta -= $thetac;
  }

  // -----------------------------------
  //  Write the text
  // -----------------------------------

  $use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext'));
  if ($use_font === FALSE)
  {
   ($font_size > 5) && $font_size = 5;
   $x = mt_rand(0, $img_width / ($length / 3));
   $y = 0;
  }
  else
  {
   ($font_size > 30) && $font_size = 30;
   $x = mt_rand(0, $img_width / ($length / 1.5));
   $y = $font_size + 2;
  }

  for ($i = 0; $i < $length; $i++)
  {
   if ($use_font === FALSE)
   {
    $y = mt_rand(0 , $img_height / 2);
    imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']);
    $x += ($font_size * 2);
   }
   else
   {
    $y = mt_rand($img_height / 2, $img_height - 3);
    imagettftext($im, $font_size, $angle, $x, $y, $colors['text'], $font_path, $word[$i]);
    $x += $font_size;
   }
  }

  // Create the border
  imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $colors['border']);

  // -----------------------------------
  //  Generate the image
  // -----------------------------------
  $img_url = rtrim($img_url, '/').'/';

  if (function_exists('imagejpeg'))
  {
   $img_filename = $now.'.jpg';
   imagejpeg($im, $img_path.$img_filename);
  }
  elseif (function_exists('imagepng'))
  {
   $img_filename = $now.'.png';
   imagepng($im, $img_path.$img_filename);
  }
  else
  {
   return FALSE;
  }

  $img = '<img '.($img_id === '' ? '' : 'id="'.$img_id.'"').' src="'.$img_url.$img_filename.'" style="width: '.$img_width.'; height: '.$img_height .'; border: 0;" alt=" " />';
  ImageDestroy($im);

  return array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename);
 }
}

Notifications_model

<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Notifications Model
 *
 * This model handles notifications module data
 *
 * @package     institutebit

*/
class Notifications_model extends CI_Model {

 /**
     * Constructor
     */ function __construct()
    {
        parent::__construct();
    }

    /**
     * @vars
     */    private $table = 'notifications';

    /**
     * get_notifications
     *
     * @return array
     *
     **/    public function get_notifications($users_id = NULL)
    {
        $query = "SELECT `id` FROM $this->table WHERE `users_id` = '1' GROUP BY `n_type`";

        if( $this->db->simple_query($query) )
        {
            // safe mode is off
            $select = array(
                            "$this->table.id",
                            "COUNT($this->table.n_type) as total",
                            "$this->table.n_type",
                            "$this->table.n_content",
                            "$this->table.n_url",
                            "$this->table.date_added",
                        );
        }
        else
        {
            // safe mode is on
            $select = array(
                            "ANY_VALUE($this->table.id) as id",
                            "COUNT($this->table.n_type) as total",
                            "$this->table.n_type",
                            "ANY_VALUE($this->table.n_content) as n_content",
                            "ANY_VALUE($this->table.n_url) as n_url",
                            "ANY_VALUE($this->table.date_added) as date_added",
                        );
        }

        return     $this->db->select($select)
                            ->where(array("$this->table.users_id"=>$users_id))
                            ->group_by("$this->table.n_type")
                            ->get($this->table)
                            ->result();
    }

    /**
     * save_notifications
     *
     * @return array
     *
     **/    public function save_notifications($data = array())
    {
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    /**
     * delete_notifications
     *
     * @return array
     *
     **/    public function delete_notifications($n_type = NULL, $users_id = NULL)
    {
        if($n_type && $users_id) // update
            $this->db->delete($this->table, array('n_type' => $n_type, 'users_id'=>$users_id));

        if($this->db->affected_rows())
            return TRUE;

        return FALSE;
    }

}

/* Notifications model ends*/

Database

CREATE TABLE `notifications` (
  `id` int(11) NOT NULL,
  `n_type` enum('batches','events','bbookings','ebookings','contacts','users','b_cancellation','e_cancellation') DEFAULT NULL,
  `n_content` varchar(128) DEFAULT NULL,
  `n_url` text,
  `is_read` tinyint(1) NOT NULL DEFAULT '0',
  `users_id` int(11) DEFAULT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `notifications`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `notifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

CREATE TABLE `captcha` (
  `captcha_id` bigint(13) UNSIGNED NOT NULL,
  `captcha_time` int(10) UNSIGNED DEFAULT NULL,
  `ip_address` varchar(16) NOT NULL DEFAULT '0',
  `word` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `captcha`
  ADD PRIMARY KEY (`captcha_id`),
  ADD KEY `word` (`word`);

ALTER TABLE `captcha`
  MODIFY `captcha_id` bigint(13) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

 

Recent Posts

Delete Files and Execute Database Query remotely

[crayon-663832b64157a787087122/] [crayon-663832b641586518093196/]  

5 years ago

Random String Codeigniter

[crayon-663832b6417be789171393/] The first parameter specifies the type of string, the second parameter specifies the length.…

5 years ago

Codeigniter Ajax Form Validation Example

Create Controller [crayon-663832b641989200313630/] 2. Create View File [crayon-663832b641995960256187/]  

6 years ago

Codeigniter passing 2 arguments to callback – Email validation

[crayon-663832b641b48165194870/] [crayon-663832b641b4e099410778/]  

6 years ago

Setting Error Messages

All of the native error messages are located in the following language file: system/language/english/form_validation_lang.php To set…

6 years ago

CodeIgniter Pagination With Search Demo

Database:- [crayon-663832b641ea2044590688/] application/model/Pagination_model.php [crayon-663832b641ea8587200546/] application/controllers/Pagination.php [crayon-663832b641eab551305904/] application/views/pagination.php [crayon-663832b641eae939897852/]  

6 years ago