Monday, March 2, 2015

Codeigniter data of birth generation and validation

User friendly date with Codeigniter and MySQL


When we deal with the date in Codeigniter and MySQL, there is a little problem that MySQL accepts dates only in the ISO-recommended format YYYY-MM-DD. I want users to be able to enter and show dates in a more familiar format.

At here if you use a text box to enter the date, user can do many mistake. So the best way to handle the input of dates is with separate fields using HTML <select> elements or combo boxes. Let's start our project.

Requirement

CodeIgniter

Step 1: Configuration

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = “localhost”;

$config['username'] = “myusername”;

$config['password'] = “mypassword”;

$config['database'] = “mydatabase”;

$config['dbdriver'] = “mysql”;

Then open application/config/config.php

$config['base_url'] = ‘http://localhost/ci_date’;

Open application/config/autoload.php

$autoload['libraries'] = array('database’);

and

$autoload['helper'] = array(‘url’,'form’);

Open application/config/routes.php, change default controller to user controller as we’ll create later on this tutorial.

$route['default_controller'] = ‘home’;

Creating Database table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `user` (
  `id` int(20) NOT NULL auto_increment,
  `name` varchar(50) NOT NULL,
  `dob` date NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Designing our date input view files

Now let's create our design file. Create a blank document in the views folder (application -> views) and name it home_view.php, in thedocument add all the following code.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
 <div id="wrapper">
 <div id="content">
 <?php $this->load->helper('dob'); ?>
 <div class="reg_form">
 <?php echo validation_errors('<p class="error">'); ?>
 <?php echo form_open("home/add_data"); ?>
  <p>
   <label for="user_name">User Name:</label>
   <input type="text" id="user_name" name="user_name" value="" />
  </p>
  <p>
   <label>Birthday:</label>
   <select name="month"><option value="0">Month:</option><?php echo generate_options(1,12,'callback_month')?></select>
   <select name="day"><option value="0">Day:</option><?php echo generate_options(1,31)?></select>
   <select name="year"><option value="0">Year:</option><?php echo generate_options(2011,1900)?></select>
  </p>
  <p>
   <input type="submit" class="greenButton" value="Submit" />
  </p>
 <?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">-->
<div id="footer">
 &copy; 2011 <a href="http://tutsforweb.blogspot.com/">TutsforWeb</a> All Rights Reserved.
</div><!-- <div class="footer">-->
</div><!--<div id="wrapper">-->
</body>
</html>

In this file, you will notice that dob helper. It is not CI built in helper. This helper is created by learning this tutorial.

Our birthday field will be look like below:

Creating dob_helper

Following code is our dob_helper.php. Create a blank document in the helpers floder (application -> helpers) and name it dob_helper.php, in the document add all the following code.

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('generate_options'))
{
 function generate_options($from,$to,$callback=false)
 {
  $reverse=false;
  if($from>$to)
  {
   $tmp=$from;
   $from=$to;
   $to=$tmp;
   $reverse=true;
  }
  $return_string=array();
  for($i=$from;$i<=$to;$i++)
  {
   $return_string[]='
   <option value="'.$i.'">'.($callback?$callback($i):$i).'</option>
   ';
  }
  if($reverse)
  {
   $return_string=array_reverse($return_string);
  }
  return join('',$return_string);
 }
}
if ( ! function_exists('callback_month'))
{
 function callback_month($month)
 {
  return date('F',mktime(0,0,0,$month,1));
 }
}
if ( ! function_exists('format_date'))
{
 function format_date($date)
 {
  $parts = explode('-',$date);
  return date('F j, Y',mktime(0,0,0,$parts[1],$parts[2],$parts[0]));
 }
}
?>

In our helper, it has three functions generate_options(), callback_month() and format_date(). We used the generate_options() and callback_month() in our html select element to fill the data. The format_date() function will be used when we display the date to the user.

Check the input date in the Controller

Create a blank document in the controllers folder (application -> controllers) and name it home.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller{
 public function __construct(){
  parent::__construct();
  $this->load->model('home_model');
 }
 public function index()
 {
  $this->load->view('home_view');
 }
 public function add_data()
 {
  $_POST['dob'] = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
  $this->form_validation->set_rules('dob', 'Date of Birth', 'callback_date_check');
  if ($this->form_validation->run() == FALSE)
  {
   $this->load->view('home_view');
  }
  else
  {
   $this->home_model->save_data();
   $this->show();
  }
 }
 public function date_check()
 {
  if(checkdate($_POST['month'],$_POST['day'],$_POST['year']))
  {
   return TRUE;
  }
  else
  {
   $this->form_validation->set_message('date_check', 'Correct you Date of Birth.');
   return FALSE;
  }
 }
 public function show()
 {
  $this->load->model('home_model');
  $data['query']=$this->home_model->get_all();
  $this->load->view('dateshow_view',$data);
 }
}
?>

In our add_data() function, firstly we set the $_POST['dob'] from our three html select boxes by concatenating '-' between them. Now our dob post data is ready to add to the MySQL database. There's just one problem with this: someone might enter an invalid date, such as February 31 or September 31. So, it's a good idea to use the PHP checkdate() function to make sure the date is valid.

So when we set the form validation rule for our dob (Date of Birth) field, we use the callback function as date_check(). You can easily follow our date_check() function I think.

Showing our user friendly date

Let's create our dateshow_view.php to test the format_date() function from our dob_helper. Create a blank document in the views folder (application -> views) and name it dateshow_view.php, in the document add all the following code.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
<div id="wrapper">
<div id="content">
 <?php $this->load->helper('dob'); ?>
 <?php    foreach($query as $row){?>
  <p>
  <?php
   echo format_date($row->dob);
  ?>
  </p>
 <?php }?>
</div>
</div>
</body>
</html>

It will display our date as below picture.


Creating Model

Our model is very simple. Create a blank document in the models folder (application -> models) and name it home_model.php, in thedocument add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 public function save_data()
 {
  $data=array(
   'name'=>$this->input->post('user_name'),
   'dob'=>$this->input->post('dob')
  );
  $this->db->insert('user',$data);
 }
 function get_all()
 {
  $query=$this->db->get('user');
  return $query->result();
 }
}

Designing with CSS

Create a folder named css in your root directory and save following code as a sytle.css.

@charset "utf-8";
/* CSS Document */
body{
 background-color:#FFF;
 font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
 font-size:16px;
 text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
 width:960px;
 margin:0 auto;
}
#content{
 width:960px;
 margin:5px;
 float:left;
}
/************************************************/
.reg_form{
 width:460px;
 padding:20px;
 margin:0 auto;
 border:3px solid #DFDFDF;
 background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbd4e5));
 background: -moz-linear-gradient(top,  #fff,  #cbd4e5);
 filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff', endColorstr='#cbd4e5');
}
.reg_form p{
 width: 300px;
 clear: left;
 margin: 0;
 padding: 5px 0 8px 0;
 padding-left: 155px;
 border-top: 1px dashed gray;
 height: 1%;
}
.reg_form label{
 font-weight: bold;
 float: left;
 margin-left: -155px;
 width: 150px;
}
input,select{
 padding:3px;
 color:#333333;
 border:1px solid #96A6C5;
 margin-top:2px;
 width:180px;
 font-size:11px;
}
select{
 width:auto;
 padding:2px;
}
.greenButton{
 width:auto;
 margin:10px 0 0 2px;
 padding:3px 4px 3px 4px;
 color:white;
 background-color:#589d39;
 outline:none;
 border:1px solid #006600;
 font-weight:bold;
}
.greenButton:active{
 background-color:#006600;
 padding:4px 3px 2px 5px;
}

dow

0 comments:

Post a Comment

Labels

.htaccess (5) 2step verification in php (1) 404 Page (1) Address Autocomplete (1) Admin (1) Ajax (3) alias key generation (1) All Browsers Testing (1) Android (19) Android 5.0 (2) Android Life Cycle (1) Android webview media capture (1) angular js (7) Angular Js ebook (1) AngularJS (23) Apache and mysql start up automatically once system boot (1) array_combine() (1) array_merge() (1) array_search() (1) async css and js (1) auto generate url slug in codeginiter (1) Auto reload (1) Autocomplete (1) automation code for php and mysql (1) AWS EC2 Hosting (5) AWS EC2 Hosting Connect with notepad++ (1) AWS ECS Hosting (1) base_url() (1) Basic php example on this keyword use (1) Best Practices to write jquery (1) Bootstrap (2) Bootstrap form tag problem (1) Bootstrap Modal (1) Bootstrap Modals (1) Breadcrumb (1) Broad band usage meter (1) Can't connect to MySQL server on (1) Cannot retrieve metalink for repository (1) Career Guidance (1) Carousel (1) Categories of websites (1) Cent OS (2) CI (1) Ci Errors (1) ckeditor (3) Clear Browser Cache Trick (1) Client IP Address (1) Code completion for codeigniter (1) Codehint for CodeIgniter (1) CodeIgniter (53) Codeigniter Controllers (1) Codeigniter email (1) Codeigniter file upload (2) Codeigniter send grid integration (1) CodeIgniter with Dreamweaver (1) color replace function in jquery (1) colorReplace function (1) configuration files locations (1) Controllers in controllers angular js (1) Cookies (1) core php file upload (1) count down timer in seconds in jquery (1) Countries Table in mysql (1) Create User in mysql Db (1) CryptoJS (1) CSS (3) CSS tricks (2) curl parallel calls (1) Currency API (1) Customize date format in php (1) Data dictionary (1) data of birth validation and generation codeigniter (1) Database backup in php (1) date (1) Date Difference (2) date difference in jquery (1) Date format in php (1) Date functions (1) datepicker date format jquery (1) Datetime Picker (1) datewise mysql backup (1) DBFunctions (1) Default Image in html (1) Desktop tricks (1) Detect Android Mobile (1) Detect Iphone using javascript (1) Disadvantages of Joomla (1) Disadvantages of Wordpress (1) Distance Calculation (1) document printing (1) Document submit (1) dreamweaver (1) Drupal CMS (2) Drupal Components (1) Drupal Update (1) Dynamic jQuery (21) Dynamic websites building (1) echo (1) editor for html interface (1) Email (2) Email extract in php (1) email php configuration (1) empty() and is_null() difference (1) error handling in php (1) event.PreventDefault() (1) execution time in javascript (1) extract numbers php (1) Facebook Link Posting (1) Facebook Login Error Javascript (1) Facebook Page Likes (1) Fancybox (1) Features of Joomla (1) Features of Wordpress (1) file upload (1) File upload in jquery (1) File upload through URL with php script (1) file_get_contents (1) Files listing from folders in php (1) FileUpload (2) fileupload in jquery with preview (1) filezilla (1) Filter to top (1) Find the Framework of a website (1) Firewall Configuration in Centos (1) FOR php developers (2) Form_validation form with codeigniter (1) FTP (1) Full calendar (1) Geo API (4) Geo Code (2) Geo complete (1) Geo Location (1) GeoLocation (4) get ipaddress (1) gmail contacts api (1) Google Chrome Install (1) Google Map (1) Google Maps (8) Grant all privileges in mysql db (1) Grocery Crud (5) Guess CMS (1) hashtag (1) History Clear (1) HMVC (1) Host is not allowed to connect to MySQL Server (1) how to include header and footer html in html (1) How to prevent sql injection in php (1) how to zip file in linux (1) HTML (4) HTML CSS JS compression (1) HTML Typography (1) HTML5 (4) httpd.conf Configurations (1) Huge IT Silder (1) Hybrid App (1) Hyperlinks (1) image resize in codeigniter (1) Image with preview and remove html (1) Include() and include_once Difference (2) India States (1) Interfaces in PHP (1) Internal server error solution (1) Invoice Templates (1) ionic (13) ionic ios (1) iOS (3) iTunes (1) Javascript (45) javascript countdown timer (1) javascript email validation (1) Javascript Object properties view (1) Javascript UNIX time stamp converter (1) Jquery (40) jquery datepicker (2) jquery detect idle state (1) jquery list sort (1) Jquery OWL Carousel (1) Jquery UI (1) jquery username validation (1) jquery validation (1) JS (1) JSON (3) Laravel (4) Laravel Tutorials (2) Latest Android Version (1) Linux commands (5) LINUX Ftp Configuration (1) Linux Server IP Address (1) List Sortable in Jquery UI (1) Lollipop (1) Magento (1) mail in php (1) main controller and child controller and another child controller (1) maximum execution time in php code (1) Media Capture in HTML5 (1) method overloading in php (1) method overriding in php (1) mod_rewrite (1) Mouse Deselection Javascript (1) Multidimensinal Array sort (1) multiple comparisons in php (1) Multiple file upload in Angular JS (1) Multiple file upload in jquery (1) multiple file upload in php (1) multiselect (1) Mysql (20) mysql and apache start up automatically once system boot (1) mysql connect (1) mysql connect in windows os (1) mysql database backup (1) mysql datatypes (1) Mysql DB (1) mysql Db connection program (1) Mysql Errors (1) mysql functions (1) MySQL HostName (1) mysql query tricks (1) MySQL server at 'reading initial communication packet' (1) mysql_real_escape_string() (1) mysql_secure_installation (1) mysql.sock (2) Error (1) mysqli (2) Native App (1) Netbeans for linux (1) Network usage monitor (1) ng-bind (1) ng-click (1) Node js (1) Notepad++ (1) onchange display images (1) Online UNIX Timestamp to human readble format converter (1) OOPS in php (1) Pagination in Codeigniter (1) Pagination in php (1) Password encryption and decryption in php (1) Paypal (1) PayU Form (1) PDF (1) PDO (2) Pendrive Data Recovery (1) php (62) PHP 5.4.0 (2) php abstract class example (1) PHP ajax file upload (2) PHP ajax request detection (1) PHP Basic Login and logout (1) PHP Codeigniter database backup code (1) PHP Contact us email form code (1) PHP corn jobs (1) php database backup script (1) php email validation (1) PHP Environment Setup (1) PHP Errors (1) PHP Extension and Application Repository) (1) php file upload (1) PHP File Uploading (1) PHP fileupload helper in codeigniter (1) PHP interview questions (4) PHP lamda functions examples (1) PHP Login (1) PHP pdo (1) PHP PDO script to insert data inside mysql db (1) PHP Random Password generation Script (2) php script execution limit (1) php script to display months (1) php script to print years as dropdown (1) PHP Storm (2) PHP Storm license key (1) PHP strong encryption and decryption (1) php timeslot generator (1) php-mysql Modules (1) phpmyadmin (2) phpMyAdmin install (1) Pin-code finder (1) Pincode (1) Play youtube video in angular JS (1) Popup (2) POPUP in javascript (1) POST and GET Difference (1) POST DATA IN PHP (1) Postfix sendmail (1) preview of selected file (1) Print content with jquery (1) print() (1) Push Notifications (1) query string based pagination in codeigniter (1) Random key (1) ratings (1) regular expressions (1) remote validation (1) remove query string (1) Remove Sale Tag or Logo of woocommerce (1) Repository (1) require_once() (1) require() (1) Resize Image Dynamically (1) result_array() (1) rpmdb open fail (1) Salaries (1) SCP Command syntax (1) select images display in webbrowser (1) Selected values in javascript (1) Send free sms (1) Send Grid (1) Send Grid Email integration (1) SEO PHP (1) Session Management in PHP (1) show active class in the url automatically php (1) Show alternate image (1) simple ajax php script (1) Simple Login in PHP (1) Simple registraion (1) single file upload (1) site2sms script (1) Slideshow (1) SMTP Configuration (2) SOFTWARE TECHNOLOGY TIPS (1) Sort list items by Mouse in jquery (1) sprintf in php (1) SQL Injection in php (1) States Countries API (1) static variable in javascript (1) store date in php (1) stripslashes() (1) strtotime (1) sum of array values (1) sumo select (1) system error: 113 (1) Text to ASCII Generator (1) this keyword (1) Time ago function in javascript (1) Time ago Plugin (1) Time in PHP (1) time picker in grocery crud admin (1) Timeslot Generation in PHP (1) Tooltips using css (1) trigger in mysql (1) ubuntu (1) UNIX timestamp to HUMan readable converter (1) use full tutorials (1) user ur domain inseted of localhost (1) validation in javascript (1) Version Controls for PHP (1) Webmin (1) What CMS (1) Why Drupal CMS (1) Windows 10 (1) Windows Commands (1) Wordpress (2) Xampp (2) Xampp Localhost (1) Xampp Security (1) Yii Framework configuration (1) Yii framework installation (1) ZipArchive (1) ZipArchive php aws (1)
 
TOP