Tagged: CodeIgniter Framework Tutorials

Data Insertion in CodeIgniter 0

Data Insertion in CodeIgniter

In this tutorial we will learn about how to insert data into database in codeIgniter.
1.Create a database then configure your db credential in application/database.php

$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost', // your hostname
	'username' => 'root', // your DB username
	'password' => '',     // DB password
	'database' => 'cidb', // your database name
	'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
);

2. load some libraries and helpers in application/autoload.php

$autoload['libraries'] = array('database','session');
$autoload['helper'] = array('html','form');
  • Database library used for database related queries
  • Session library  used for display success / error message using flashdata.
  • Html Helper for used for link_tag
  • form helper used for form

First create a  view(registration.php) inside application/view folder

<?php echo form_open('registration',['name'=>'registration'])?>
<!---- Success Message ---->
<?php if ($this->session->flashdata('success')) { ?>
 <p style="color:red; font-size:16px; "><?php echo $this->session->flashdata('success'); ?></p>
<?php } ?>
<!---- Error Message ---->
<?php if ($this->session->flashdata('error')) { ?>
<p style="color:red; font-size:16px;"><?php echo $this->session->flashdata('error'); ?></p>
<?php } ?>
<p>
<?php echo form_label('Enter your Name', 'name'); ?>
<?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter you full name','value'=>set_value('fullname')]);?>
<?php echo form_error('fullname',"<div style='color:red'>","</div>");?>
</p>
<p>
<?php echo form_label('Enter your Contact Mobile Number', 'mobnumber'); ?>
<?php echo form_input(['name'=>'mobnumber','id'=>'mobnumber','placeholder'=>'Enter your Contact Mobile Number','value'=>set_value('mobnumber')]);?>
<?php echo form_error('mobnumber',"<div style='color:red'>","</div>");?>
</p>
<p>
<?php echo form_label('Enter your Valid Email id', 'emailid'); ?>
<?php echo form_input(['name'=>'emailid','id'=>'emailid','placeholder'=>'Enter your Valid Email id','value'=>set_value('emailid')]);?>
<?php echo form_error('emailid',"<div style='color:red'>","</div>");?>
</p>
<p>
<?php echo form_label('Select gender','gender'); ?> :
<?php
$options=array(
'Male'=>'Male',
'Female'=>'Female',
'Other'=>'Other'
);
echo form_dropdown('gender',$options);?>
</p>
<p>
<?php echo form_label('Enter your address','address'); ?> <br />
<?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'60','id'=>'address','class'=>'form-control','placeholder'=>'Enter your address','value'=>set_value('address')]);?>
<?php echo form_error('address',"<div style='color:red'>","</div>");?>
</p>
<p class="termcondtion">
<?php echo form_checkbox('TermsCondition','accept', TRUE); ?>
<?php echo form_label('Accept terms and conditions','terms'); ?>
</p>
<p class="login button">
<?php echo form_submit(['name'=>'submit','value'=>'Submit']);?>
</p>
</form>
<?php echo form_close();?>

Now create a controller (Registration.php) inside application/controller. You can also set your default controller in application/routes.php

$route['default_controller'] = 'Registration';
<?php
Class Registration extends CI_Controller{
public function index(){
//library form validation . you can also load this libray in application/autoload.php
$this->load->library('form_validation');
$this->form_validation->set_rules('fullname','Full Name','required');
$this->form_validation->set_rules('mobnumber','Mobile Number','required|numeric|exact_length[10]');
$this->form_validation->set_rules('emailid','Email id','required|valid_email');
$this->form_validation->set_rules('address','Address','required');
if($this->form_validation->run()){
$fname=$this->input->post('fullname');
$mnumber=$this->input->post('mobnumber');
$emaild=$this->input->post('emailid');
$gender=$this->input->post('gender');
$adress=$this->input->post('address');
$tc=$this->input->post('TermsCondition');
$this->load->model('Registration_Model');
$this->Registration_Model->insertdata($fname,$mnumber,$emaild,$gender,$adress,$tc);
}
else{
$this->load->view("registration");
}
}

Create a model (Registration_Model.php) inside application/model.

<?php
Class Registration_Model extends CI_Model{
public function insertdata($fname,$mnumber,$emaild,$gender,$adress,$tc){
$data=array(
			'fullName'=>$fname,
			'mobileNumber'=>$mnumber,
			'emailId'=>$emaild,
			'gender'=>$gender,
			'address'=>$adress,
			'termsCondition'=>$tc
		);
$sql_query=$this->db->insert('tblusers',$data);
if($sql_query){
$this->session->set_flashdata('success', 'Registration successful');
redirect('registration');
}
else{
$this->session->set_flashdata('error', 'Somthing went worng. Error!!');
redirect('registration');
}}
}

SQL Table structure for tblusers

CREATE TABLE `tblusers` (
  `id` int(11) NOT NULL,
  `fullName` varchar(150) DEFAULT NULL,
  `mobileNumber` char(12) DEFAULT NULL,
  `emailId` varchar(50) DEFAULT NULL,
  `gender` varchar(30) DEFAULT NULL,
  `address` mediumtext,
  `termsCondition` varchar(200) DEFAULT NULL,
  `postingDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

View Demo———————————————–

How to run this script

  1. Download the zip file .
  2. Extract the zip and copy registrationci folder
  3. Paste in root directory(For xampp htdocs and for wamp www)
  4. Open your browser put http://localhost/phpmyadmin
  5. Create a database cidb
  6. Import sql file tblusers.sql
  7. Run your script http://localhost/registrationci

Data Insertion in CodeIgniter (Download full source code)
Size: 2.76 MB
Version: v 1

Active records in CodeIgniter 0

Active Record in CodeIgniter

CodeIgniter uses a modified version of the Active Record Database Pattern. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action. CodeIgniter does not require that each database table be its own class file. It instead provides a more simplified interface.
Selecting data
All of the functions in this section will build SQL SELECT queries. All of the SQL in this section is MySQL; other database systems may differ slightly.
$this->db->get();
The simplest query that you can do with Active Record is to select a full database table. This is done with one single function:

$this->db->get();

This would create the SQL query:

SELECT * FROM `table_name`;

This function has three parameters. The first is the name of the database table. The second lets you set a limit, and the third lets you set an offset.

$query = $this->db->get('table_name', 10, 20);

This would then produce the SQL query:

SELECT * FROM `table_name` LIMIT 20, 10;

$this->db->get_where();
This function works in much the same way as the previous function. The only difference is that the second parameter should be passed as an array. The array should have the name of the field and the value to use to fill in the WHERE part of your query.

$query = $this->db->get('table_name', array('id' => $id), 10, 20);

This would produce the following SQL query:

SELECT * FROM 'table_name' WHERE 'id' = $id LIMIT 10, 20;

$this->db->select();
This function allows you to write the SELECT portion of your query. Take a look at the following example:

$this->db->select('name, username, email');
$query = $this->db->get('users');

The SQL query produced from this function will be :

SELECT name, username, email FROM `users`;

You should take note that when using this function, and any of the other functions that let you write a portion of your query, that you still need to use the get() function to actually produce and run the query.

If you are selecting everything form your database (*) then you do not need to use this function as CodeIgniter assumes that you mean to select everything.

$this->db->from();
This function allows you to write the FROM portion of your query. This is basically the same as using the get() function, although it is slightly more readable. You can use whichever method you prefer.

$this->db->from('table_name');
$query = $this->db_>get();

$this->db->join();
This function lets you write the JOIN part of your query. Here’s an example:

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

You can specify a different type of join in the third parameter. You can choose from left, right, outer, inner, left outer, and right outer.

$this->db->join('comments', 'comments.id = blogs.id', 'left');

$this->db->where();
This function is used to build the WHERE portion of your query. This function can be used in a variety of ways.
Single key or value method

$this->db->where('name', $name);

Multiple key or value method

$this->db->where('name', $name);
$this->db->where('email', $email);

Associative array method
You can pass values to the where() function by using an associative array. Take a look at the following example:

$array = array('name' => $name, 'email' => $email);
$this->db->where($array);

You can include operators in the array, just as you would use in the first parameter.

$array = array('name !=' => $name, 'email' => $email);
$this->db->where($array);

$this->db->like();
This function allows you to write the LIKE portion of your query, and functions in almost the exact same way as the where() method.
Single key or value method
This method is the same as the where() method, when used as follows:

$this->db->like('name', $name);

Multiple key or value method
This method is also the same as the where() method. Multiple calls will be chained together.

$this->db->like('name', $name);
$this->db->like('email', $email);

$this->db->group_by();
This function lets you write the GROUP BY portion of your query.

$this->db->group_by('name');
$this->db->group_by(array('name', 'title'));

$this->db->order_by();
This lets you write the ORDER BY portion of your query. The first parameter is for your field name. The second is the type of order that you want to use, and can be asc, desc, or random.

$this->db->order_by('name', 'desc');

You can also pass a string as the first parameter.

$this->db->order_by('name desc, title asc');

Multiple function calls can also be used, as for other functions.

$this->db->order_by('name', 'desc');
$this->db->order_by('title', 'asc');

$this->db->limit();
This function lets you add a LIMIT specification to your query. The first parameter will be the number to limit to, and the second parameter let’s you set an offset.

$this->db->limit(10, 20);

Inserting data
Inserting data using Active Record is a very simple process, and there are just two functions that you may need to use in order to insert data into your database.

$this->db->insert();

This will generate an insert string based upon the data that you supply to it. The first parameter is the name of the table that you want to add the data to, and the second parameter can either be an array or an object of the data.

$data = array('name' => 'Bob Smith',
'email' => 'bob@smith.com');
$this->db->insert('table_name', $data);

This would then produce the following SQL statement:

INSERT INTO mytable (name, email)
VALUES ('Bob Smith', 'bob@smith.com');

$this->db->update();
This will generate an update string based upon the data that you supply to it.
The first parameter is the name of the table you want to add the data to, and the second parameter can either be an array or an object of the data. The third,
optional parameter enables you to set the WHERE clause of your SQL query.

$data = array('name' => 'Bob Smith','email' => 'bob@smith.com');
$this->db->where('id', 5);
$this->db->update('table_name', $data);

This would then produce the following SQL statement:

UPDATE mytable SET name = 'Bob Smith', email = 'bob@smith.com';

You can optionally use the where() method to set the where clause of the query. Here’s how you would use the third parameter to set the WHERE clause:

$data = array('name' => 'Bob Smith','email' => 'bob@smith.com');
$this->db->update('table_name', $data, 'id = 5');

$this->db->delete();
This function accepts two parameters. The first is the name of the table, and the second should be an array from which to build the WHERE clause.

$this->db->delete('table_name', array('id' => 5));

You can also use the where() function to build the WHERE clause:

$this->db->where('id', 5);
$this->db->delete('table_name');

An array of table names can be passed into this function, if you wish to delete more than one table.

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

Source https://www.codeigniter.com/userguide2/database/active_record.html

Database interaction in CodeIgniter 0

Database interaction in CodeIgniter

Databases are the backbone behind any Web application. Without a database, you’d have nowhere to hold all of your data, and SQL queries can become long and cumbersome to type out. Thankfully, CodeIgniter gives us a brilliantly simple way to interact with our Database. The database library also makes changing between database types—from MySQL to Oracle, for example—easier, because it acts as a wrapper and provides many functions for us to use on the database.
Loading the library
Loading the Database library is slightly different from loading other libraries. This is because it is large and resides in a different folder, unlike the other libraries.

$this->load->database();

Performing simple queries
CodeIgniter gives us a function that we can pass a SQL Query to, and the query will be run on the  database. Here’s how it works:

$this->db->query('PUT YOUR SQL HERE');

This function is simple to use; you simply use this function in place of any native PHP functions you would use to run queries. This function will return TRUE or FALSE for write queries, and will return a dataset for read queries.
There is another function that you can use for very simple queries; this will only return TRUE or FALSE. It won’t let you cache your query or run the query timer.  In most cases you won’t want to use this function.

$this->db->simple_query('PUT YOUR SQL HERE');

The SQL code that you pass to these functions are database-dependent. Only Active Record queries are independent of any type of Database SQL.
Returning values
You can assign the function $this->db->query() to a variable. You can then run a number of helper functions on the variable in order to return the data in different formats. Take the following example:

$query = $this->db->query('SELECT * FROM 'users'')

Returning a result object
In this case, returning the result will return an array of objects, or an empty array if the query failed. You would usually use this function in a foreach loop.

foreach($query->result() as $row)
{ 
echo $row->username; 
echo $row->email;
 }

If your query does not return a result, the CodeIgniter User Guide encourages you to check for a failure before using this function.

if($query->num_rows > 0)
{ 
foreach($query->result() as $row){  
echo $row->username;    
echo $row->email;
}
}

Returning a result array You are also able to return the result dataset as an array. Typically, you would use this function inside a foreach loop as well.

foreach($query->result_array() as $row){
echo $row['username']; 
echo $row['email'];
 }

Returning a row object
If your query is only expected to return a single result, you should return the row by using the following function. The row is returned as an object.

if($query->num_rows() > 0){
$row = $query->row();   
echo $row->username;
echo $row->email;
}

You can return a specific row by passing the row number as a digit in the  first parameter.

$query->row(2);

Returning a row array
You can return a row as an array, if you prefer. The function is used in the same way as the previous example.

if($query->num_rows() > 0){ 
$row = $query->row_array();   
echo $row['username'];
echo $row['email'];
 }

You can return a numbered row by passing the digit to the first parameter, also.

$query->row_array(2);

Result helper functions
Besides the helper function that helps to return the dataset in different ways, there are some other more generalized helper functions.
 Number of rows returned
Used in the same way as the other helper functions, this will return the total number of rows returned from a query. Take the following example:

echo $query->num_rows();

Number of fields returned
Just like the previous function, this will return the number of fields returned by  your query.

echo $query->num_fields();

Free result
This function will remove the resource ID associated with your query, and free the associated memory. PHP will usually do this by default, although when using many queries you may wish to use this to free up memory space.

$query->free_result();
Form Validation in CodeIgniter 3

Form Validation in CodeIgniter

A form is displayed to the user, who then fills it in and submits it. The Form Validation Library then checks the form against any rules that the developer has set. If an error occurs the library returns these errors and they are shown against the form with the fields re-populated. This process proceeds until a valid form is submitted.
The development process
You create a form, along with a dynamic value from a form helper function—this will re-populate the data if needed. You will also display individual or global errors in the form view file. You set validation rules, which must be adhered to. Then you check to see if the validation process has been run, and if it has not, you load the form view file.
Loading the assets
We need to load one libraries for form validation: the Form Validation Library. We can do this in one line

$this->load->library('form_validation');

Setting the rules
The next step in using the Form Validation Library is to set the rules for the form. These rules are set and must be adhered to. The way we set rules is by using the
set_rules() function of the Form Validation Library. We use the function
as follows:

$this->form_validation->set_rules('field_name', 'human_name', 'rules');

As you can see, the function accepts three parameters. The first is the name of the form field that you wish to set the rule for. The second parameter is the name that you wish to be assigned to this, for humans to read. The final parameter is where you pass any validation rules.
List of validation rules
The following rules are readily available for use:

  • required
  • matches[field_name]
  • min_length[x]
  • max_length[x]
  • exact_length[x]
  • alpha
  • alpha_numeric
  • alpha_dash
  • numeric
  • integer
  • is_natural
  • is_unique
  • is_natural_no_zero
  • valid_email
  • valid_emails
  • valid_ip
  • valid_base64

The following is a list of all the native rules that are available to use:

Rule Parameter Description Example
required No Returns FALSE if the form element is empty.  
matches Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item]
regex_match Yes Returns FALSE if the form element does not match the regular expression. regex_match[/regex/]
differs Yes Returns FALSE if the form element does not differ from the one in the parameter. differs[form_item]
is_unique Yes Returns FALSE if the form element is not unique to the table and field name in the parameter. Note: This rule requires Query Builder to be enabled in order to work. is_unique[table.field]
min_length Yes Returns FALSE if the form element is shorter than the parameter value. min_length[3]
max_length Yes Returns FALSE if the form element is longer than the parameter value. max_length[12]
exact_length Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8]
greater_than Yes Returns FALSE if the form element is less than or equal to the parameter value or not numeric. greater_than[8]
greater_than_equal_to Yes Returns FALSE if the form element is less than the parameter value, or not numeric. greater_than_equal_to[8]
less_than Yes Returns FALSE if the form element is greater than or equal to the parameter value or not numeric. less_than[8]
less_than_equal_to Yes Returns FALSE if the form element is greater than the parameter value, or not numeric. less_than_equal_to[8]
in_list Yes Returns FALSE if the form element is not within a predetermined list. in_list[red,blue,green]
alpha No Returns FALSE if the form element contains anything other than alphabetical characters.  
alpha_numeric No Returns FALSE if the form element contains anything other than alpha-numeric characters.  
alpha_numeric_spaces No Returns FALSE if the form element contains anything other than alpha-numeric characters or spaces. Should be used after trim to avoid spaces at the beginning or end.  
alpha_dash No Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.  
numeric No Returns FALSE if the form element contains anything other than numeric characters.  
integer No Returns FALSE if the form element contains anything other than an integer.  
decimal No Returns FALSE if the form element contains anything other than a decimal number.  
is_natural No Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.  
is_natural_no_zero No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.  
valid_url No Returns FALSE if the form element does not contain a valid URL.  
valid_email No Returns FALSE if the form element does not contain a valid email address.  
valid_emails No Returns FALSE if any value provided in a comma separated list is not a valid email.  
valid_ip Yes Returns FALSE if the supplied IP address is not valid. Accepts an optional parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format.  
valid_base64 No Returns FALSE if the supplied string contains anything other than valid Base64 characters.

Source : https://www.codeigniter.com/userguide3/libraries/form_validation.html
As you can see, some of these rules have a single parameter.
The rule matches[] will return TRUE if the field matches the field name passed to it.
The min_length[], max_length[], and exact_length[] rules will take an integer as a parameter and check if the minimum length, maximum length respectively, or exact length matches the rule.
The rules with no parameters are pretty much self-explanatory. You are able to use more than one rule, simply separate rules with a vertical bar ‘|’ and they will cascade.
The rules
Now that we know how to set rules and what the rules we can use are, we can go ahead and set the rules necessary for our form. All fields should be required, and the e-mail field should be validated to ensure that the e-mail address is correctly formatted.

$this->form_validation->
set_rules('fullname', 'Full Name', 'required|alpha');
$this->form_validation->
set_rules('email', 'Email Address',
'required|valid_email');
$this->form_validation->
set_rules('phonenumber', 'Phone Number', 'required|numeric|exact_length[10]');
$this->form_validation->
set_rules('username', 'User Name', 'required|alpha_numeric|min_length[6]|min_length[12]');

Check the validation process
Instead of checking one of the form field’s POST value to check if the form has been submitted, we simply check to see if the Form Validation Library has run. We do this by using the following code:

if($this->form_validation->run())
{
// get the post values
}
else
{
//load the form
}

Example 1
Create a view signup_form view

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>CodeIgniter Form Validation Tutorial</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<section id="login">
    <div class="container">
    	<div class="row">
    	    <div class="col-xs-12">
        	    <div class="form-wrap">
                <h1>Signup Form</h1>
<?php echo form_open('signupform',['name'=>'signup']);?>
<?php echo validation_errors('<div style="color:red">', '</div>'); ?>
<div class="form-group">
<?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter your full name','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_input(['name'=>'email','id'=>'email','placeholder'=>'Enter your valid email','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_input(['name'=>'phonenumber','id'=>'phonenumber','placeholder'=>'Enter your 10 digit mobile number','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_input(['name'=>'username','id'=>'username','placeholder'=>'Enter your username','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_password(['name'=>'password','id'=>'password','placeholder'=>'Enter your password','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_password(['name'=>'cpassword','id'=>'cpassword','placeholder'=>'Confirm your password','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'10','id'=>'address','class'=>'form-control','placeholder'=>'Enter your address']);?>
</div>
<?php echo form_submit(['name'=>'submit','value'=>'Submit','class'=>'btn btn-custom btn-lg btn-block']);?>
                <?php echo form_close();?>
        	    </div>
    		</div> <!-- /.col-xs-12 -->
    	</div> <!-- /.row -->
    </div> <!-- /.container -->
</section>
</body>
</html>

Create signupform controller and don’t forget to load form_validation library

<?php
class Signupform extends CI_Controller {
public function __construct() {
parent::__construct();
       $this->load->library('form_validation');
}
public function index(){
$this->form_validation->set_rules('fullname','Full Name','required|alpha');
$this->form_validation->set_rules('email','Email id','required|valid_email');
$this->form_validation->set_rules('phonenumber','Phone Number','required|numeric|exact_length[10]');
$this->form_validation->
set_rules('username','User name','required|alpha_numeric|min_length[6]|max_length[12]|is_unique[tblusers.username]');
$this->form_validation->set_rules('password','Password','required|min_length[6]');
$this->form_validation->set_rules('cpassword','Confirm Password','required|min_length[6]|matches[password]');
if($this->form_validation->run()){
	echo "Form submitted";
}
else{
	$this->load->view("signup_form");
}
}
}

This method will show all errors at one place like this :
Form Validation Error1
If you want to print an error below partcular field then use form_error function.

<?php echo form_error('field name', '<div class="error">', '</div>'); ?>

Ex2 :
Signup_form view

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>CodeIgniter Form Validation Tutorial</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<section id="login">
    <div class="container">
    	<div class="row">
    	    <div class="col-xs-12">
        	    <div class="form-wrap">
                <h1>Signup Form</h1>
<?php echo form_open('signupform',['name'=>'signup']);?>
<div class="form-group">
<?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter your full name','class'=>'form-control']);?>
<?php echo form_error('fullname','<div style="color:red">', '</div>'); ?>
</div>
<div class="form-group">
<?php echo form_input(['name'=>'email','id'=>'email','placeholder'=>'Enter your valid email','class'=>'form-control']);?>
<?php echo form_error('email','<div style="color:red">', '</div>'); ?>
</div>
<div class="form-group">
<?php echo form_input(['name'=>'phonenumber','id'=>'phonenumber','placeholder'=>'Enter your 10 digit mobile number','class'=>'form-control']);?>
<?php echo form_error('phonenumber','<div style="color:red">', '</div>'); ?>
</div>
<div class="form-group">
<?php echo form_input(['name'=>'username','id'=>'username','placeholder'=>'Enter your username','class'=>'form-control']);?>
<?php echo form_error('username','<div style="color:red">', '</div>'); ?>
</div>
<div class="form-group">
<?php echo form_password(['name'=>'password','id'=>'password','placeholder'=>'Enter your password','class'=>'form-control']);?>
<?php echo form_error('password','<div style="color:red">', '</div>'); ?>
</div>
<div class="form-group">
<?php echo form_password(['name'=>'cpassword','id'=>'cpassword','placeholder'=>'Confirm your password','class'=>'form-control']);?>
<?php echo form_error('cpassword','<div style="color:red">', '</div>'); ?>
</div>
<div class="form-group">
<?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'10','id'=>'address','class'=>'form-control','placeholder'=>'Enter your address']);?>
</div>
<?php echo form_submit(['name'=>'submit','value'=>'Submit','class'=>'btn btn-custom btn-lg btn-block']);?>
                <?php echo form_close();?>
        	    </div>
    		</div> <!-- /.col-xs-12 -->
    	</div> <!-- /.row -->
    </div> <!-- /.container -->
</section>
</body>
</html>

Controller will be the same for both methods.
Output for Ex2 will be like this:
Form Validation Error2

CI Form Validation (Download script 1)
Size: 2.61 MB
Version: V 1.0

CI Form Validation (Download script 2)
Size: 2.61 MB
Version: V 1.)

How to create form in CodeIgniter 0

How to create form in CodeIgniter

For working with form in CodeIginter you have to use form helper.
Load the form helper

$this->load->helper('form');

You can also load the form helper in application/config/autoload.php.

$autoload['helper']=array('form');

Benefit of loading form  helper in the autoload.php is that if you have multiple forms then you have to use form helper in every controller but loading form helper in autoload.php  then no need to load form helper in every controller. It will automatically autoload in every controller.
How to start a form

<?php echo form_open($action,[$attributes])?>

$action (string) : Main controller
$attributes (array) : HTML attributes like name, class etc.
For ex :

<?php echo form_open('controller/method',['name'=>'signup'])?>

This will produce

<form name="signup" method="post">

How to create an input text field 

<?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter your full name','class'=>'form-control']);?>

This will produce

<input type="text" name="fullnmae" id="fullname" placeholder="Enter your full name" class="form-control">

How to create a password text field 

<?php echo form_password(['name'=>'password','id'=>'password','placeholder'=>'Enter your password','class'=>'form-control']);?>

This will produce

<input type="password" name="password" id="password" placeholder="Enter your password" class="form-control">

How to create drop-down list

<?php echo form_dropdown('name',$options,$selectedvalues)?>

name : Name of the drop-down list
$options : list of the dropdowns
$selectedvalues :  If you wish to be selected a value
Ex for dropdwon list : 

<?php
$options=array(
'PHP'=>'PHP'
'MySQL'=>'MySQL'
'Wordpress'=>'Wordpress'
'HTML'=>'HTML'
);
echo form_dropdown('skill',$options);?>

This will produce like

<select name='skill'>
<option value="PHP">PHP</option>
<option value="MySQL">MySQL</option>
<option value="Wordpress">Wordpress</option>
<option value="HTML">HTML</option>
</select>

If you wish to a selected one value

<?php
$options=array(
'PHP'=>'PHP'
'MySQL'=>'MySQL'
'Wordpress'=>'Wordpress'
'HTML'=>'HTML'
);
echo form_dropdown('skill',$options,'PHP');?>

This will produce like

<select name='skill'>
<option value="PHP" selected='selected'>PHP</option>
<option value="MySQL">MySQL</option>
<option value="Wordpress">Wordpress</option>
<option value="HTML">HTML</option>
</select>

If you wish to  selected multiple values

<?php
$options=array(
'PHP'=>'PHP'
'MySQL'=>'MySQL'
'Wordpress'=>'Wordpress'
'HTML'=>'HTML'
);
$selectedskills=array('PHP','MySQL');
echo form_dropdown('skill',$options,$selectedskills);?>

This will produce like

<select name='skill'>
<option value="PHP" selected='selected'>PHP</option>
<option value="MySQL" selected='selected'>MySQL</option>
<option value="Wordpress">Wordpress</option>
<option value="HTML">HTML</option>
</select>

How to create radio button

<?php echo form_radio($data,$values,$checked=false/true,$extras); ?>

$data (array) : Field  data
$values (string) : Field  value
$checked : whether this radio button being checked
$extras :  Extra attributes
Ex :

<?php echo form_radio('Gender','Male',TRUE)?>
<?php echo form_radio('Gender','Female',FALSE)?>

This will produce like

<input type="radio" name="gender" value="Male" checked="checked">
<input type="radio" name="gender" value="Female">

How to create checkbox

<?php echo form_checkbox($data,$values,$checked=false/true,$extras); ?>

$data (array) : Field  data
$values (string) : Field  value
$checked : whether this check box being checked
$extras :  Extra attributes
Ex :

<?php echo form_checkbox('TermsCondition', 'accept', TRUE); ?>

This will produce like

<input type="checkbox" name="TermsCondition" value="accept" checked="checked">

How to create textarea

<?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'10','id'=>'address']);?>

This will produce like

<textarea name="address" rows="5" cols="10" id="address"></textarea>

How to create submit button

<?php echo form_submit('name'=>'submit','value'=>'Submit',class="form-btn");?>

This will produce like

<input type="submit" name="submit" value="Submit" class="form-btn" >

How to create the reset button

<?php echo form_button('name'=>'reset','value'=>'Reset','type'=>'reset',class="form-btn");?>

This will produce like

<input type="submit" name="submit" value="Submit" class="form-btn" >

How to close a form
form_close function used to close form.

<?php echo form_close( ); ?>

Full-Form scripts

First load form helper in application/config/autoload.php.

$autoload['helper']=array('form');

then create a controller  (Signupform.php)

<?php
class Signupform extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index(){
// loadin from view
$this->load->view("signup_form");
}
}

Now to form view(signup_form.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>CodeIgniter Form Tutorial</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<section id="login">
    <div class="container">
    	<div class="row">
    	    <div class="col-xs-12">
        	    <div class="form-wrap">
                <h1>Signup Form</h1>
    <?php echo form_open('signupform',['name'=>'signup']);?>
<div class="form-group">
<?php echo form_input(['name'=>'fullname','id'=>'fullname','placeholder'=>'Enter your full name','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php echo form_password(['name'=>'password','id'=>'password','placeholder'=>'Enter your password','class'=>'form-control']);?>
</div>
<div class="form-group">
<?php
$options=array(
'PHP'=>'PHP',
'MySQL'=>'MySQL' ,
'Wordpress'=>'Wordpress' ,
'HTML'=>'HTML'
);
echo form_dropdown('skill',$options,'','class="form-control"');?>
</div>
<div class="form-group">
<?php echo form_radio('Gender','Male',TRUE)?>Male
<?php echo form_radio('Gender','Female',FALSE)?> Female
</div>
<div class="form-group">
<?php echo form_textarea(['name'=>'address','rows'=>'5','cols'=>'10','id'=>'address','class'=>'form-control','placeholder'=>'Enter your address']);?>
</div>
<div class="form-group">
<?php echo form_checkbox('TermsCondition', 'accept', TRUE); ?>Terms & Conditions
</div>
<?php echo form_submit(['name'=>'submit','value'=>'Submit','class'=>'btn btn-custom btn-lg btn-block']);?>
<?php echo form_reset(['name'=>'rest','value'=>'Reset','class'=>'btn btn-custom btn-lg btn-block']);?>
                <?php echo form_close();?>
        	    </div>
    		</div> <!-- /.col-xs-12 -->
    	</div> <!-- /.row -->
    </div> <!-- /.container -->
</section>
</body>
</html>

 

CodeIgniter Form (Download Script)
Size: 2.60 MB
Version: 1

CodeIgniter plugins 0

CodeIgniter Plugins

Plugins work in almost exactly the same way as Helpers. The main difference is that a plugin should be used to add a single function, instead of a collection of functions.Helpers are also considered to be part of the core framework, whereas plugins are intended to be created and shared by the community. Plugins are stored inside the
system/application/plugins/ folder.
Loading a plugin
Loading a plugin is almost the same as loading a helper. The only difference is the function used.

$this->load->plugin('name');

Where name is the name of the plugin you wish to load.
Loading multiple plugins
To load more than one plugin, simply pass an array to the load function.

$this->load->plugin( array('name1', 'name2', 'name3') );

Using a plugin
Once a plugin is loaded, you simply call it in the same way as you would call a standard PHP function.

0

CodeIgniter View

    1. A view is a web page that display all the elements of User Interface. View deals with the front-end operations. View display data and capture user action. View send user action to controller. Location of  all view files is applications/views.

View could not be called directly. You need to load the view through controller.

How to create view

Create a HTML page and name it firstview.php. Save this file inside  applications/views.
Code of the firstview.php file.

<html>
<head>
<title>CodeIgniter View</title>
</head>
<body>
<h1>Welcome to PHPGurukul Programming Blog</h1>
</body>
</html>

Load the view

View will be load through controller.  Syntax for loading view will be :

$this->load->view('name of the view');

For our case syntax will be :

$this->load->view('firstview');

Load multiple views in Controller

<?php
class Blog extends CI_Controller {
    public function index()
    {
        $this->load->view('header');
        $this->load->view('body');
        $this->load->view('footer');
    }
}

You can also create a new folder inside application/view and save your files in this folder.

Sort views in Subfolders

You can  sort views within subfolders:

$this->load->view(‘directory_name/file_name’);

Pass Dynamic Data to view

Data can be transfer from controller to view by using an array or object.

<?php
class Blog extends CI_Controller {
    public function index()
    {
        $data['title'] = "CodeIgniter View";
        $data['heading'] = "Welcome to PHPGurukul";
        $this->load->view('firstview', $data);
    }
}

View will be look like this :

<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
</body>
</html>
CodeIgniter Model 0

CodeIgniter Model

Models deals with back end operations. Fetch data from the database and send it to the controller. All database related manipulation is done by CI Model.
For ex –  Select, Fetching records, update, and delete.
The location of all model files is applications/models and the CI model is control and accessed by controller.
How to use CI Models

  • Load database library
  • Define database configuration  in database.php file
  • Create a Model
  • How to load model in Controller

Load database library

$this->load->database();

You have to define the above library in every model if you want to reduce the lines of code then you can define database library in autoload.php file. Open application/config/autoload.php and add the database library in the library array().

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

How to Define database connection
Open applications/config/database.php and define database configuration.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost', // Your Hostname
	'username' => 'root', // Database User name
	'password' => '',     // Database password
	'database' => 'DBNAME', // Database Name
	'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
);

How to create CI Model

  • Model Class will be created inside the application/model folder.
  • You can also create a new folder inside application/model and save your files in this folder.
  • Model class will be inherit  from its base class CI_Model.
  • Use active record database pattern.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Empdata_Model extends CI_Model{
public function getempdata(){
$query=$this->db->select('Columnname1,Columnname2,Columnname3,Columnname4')
                ->where('columnname','Column Value');
                 ->get('tablename');
return $query->result();
}
}

How to load model in the controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Empdata extends CI_Controller{
public function index(){
$this->load->model('Empdata_Model');// model name
$this->Empdata_Model->getempdata();// Model method
}
}
1

CodeIgniter Controllers

Controllers take care of moving the data between the model and the views and directing traffic
based on user actions. For example, when a user submits a form, the controller collects the data and
shuffles it off to the model, which should ensure the data is valid. The controller then tells the View
(or JavaScript layer) whether it was successful.
How Controllers Work 
Before I explain how, let’s  look at the routes.php file. This file of this  Application->Config>routes.php.
Routes.php File
when we browse http://localhost/codeigniter/, CI will look for the welcome controller and by default call the index method.
If we add an entry in routes.php

$route['home_page'] = 'welcome/home_page';

then browse url http://localhost/codeigniter/home_page, CI will look for a method name home_pagein Welcome controller.
Source code of Welcome controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
	public function index()
	{
		$this->load->view('welcome_message');
	}
}

 class Welcome extends CI_Controller:  class Welcome extends(inherit)  the CI core controller.
public function index() :  This function is executed when the home page  is browsed.