CodeIgniter Insert, Update, Delete, Form validation, Pagination

CodeIgniter Insert, Update, Delete, Form validation, Pagination

Step 1) Create Table :

First, we need one table for the store out data. Below table query is given use that.

CREATE TABLE IF NOT EXISTS `shades` (
`shade_id` int(11) NOT NULL AUTO_INCREMENT,
`shade_name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`shade_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1014 DEFAULT CHARSET=latin1;




 

Step 2)  Make view :

Make html form design using boostrap. Code Given below just copy and save file in view folder and give name add_shade_view.php

<div id=”page-wrapper”>
<div class=”row”>
<div class=”col-lg-12″>
<h1 class=”page-header”>Shade</h1>
</div>
<!– /.col-lg-12 –>
</div>
<!– /.row –>
<div class=”row”>
<div class=”col-lg-12″>
<div class=”panel panel-default”>
<div class=”panel-heading”>
Add new shade
</div>
<div class=”panel-body”>
<div class=”row”>
<div class=”col-lg-6″>
<?php if($error=$this->session->flashdata(‘error’)):
$errorClass=$this->session->flashdata(‘error-class’);
?>
<div class=”alert <?=$errorClass?> alert-dismissable”>
<button type=”button” class=”close” data-dismiss=”alert” aria-hidden=”true”>×</button>
<?php print_r($error); ?>
</div>
<?php endif; ?>
<?php echo form_open(‘shade/store_shade’); ?>
<div class=”form-group”>
<label>Shade</label>
<?php echo form_input([‘name’=>’shade_name’,’class’=>’form-control’,’placeholder’=>’Enter shade name’,’autofocus’=>’autofocus’,’value’=>set_value(‘shade_name’)]);?>
<?php
echo form_error(‘shade_name’) ;
?>
</div>
<?php echo form_submit([‘name’=>’save’,’value’=>’Save’,’class’=>’btn btn-primary’]); ?>
<a href=”<?= base_url(‘shade/shade_list’);?>” class=”btn btn-default”>Back</a>
<?= form_close();?>
</div>
</div>
<!– /.row (nested) –>
</div>
<!– /.panel-body –>
</div>
<!– /.panel –>
</div>
<!– /.col-lg-12 –>
</div>
<!– /.row –>

</div>
<!– /#page-wrapper –>


Step 3)  Make Controller :

Make Controller file file for shade. Code Given below just copy and save file in controller folder and give name Shade.php

<?php
class Shade extends CI_Controller{

function __construct()
{ // check admin is login or not ?
parent::__construct();
if(!$this->session->userdata(‘admin_id’))
return redirect(‘admin_in/’);
}

public function index()
{ // redirect to login screen
if($this->session->userdata(‘admin_id’))
//return redirect(‘admin/dashboard’);
return redirect(‘admin/Employee’);

$this->load->helper(‘form’); // autoload
$this->load->view(‘admin/login’);
}

public function shade_list(){

$this->load->model(‘Shade_model’);

$this->load->library(‘pagination’);

$config = [
‘base_url’ => base_url(‘shade/shade_list’),
‘per_page’ => 20,
‘total_rows’ => $this->Shade_model->num_rows(),
‘num_links’ => 9,
‘full_tag_open’ => “<ul class=’pagination’>”,
‘full_tag_close’ => “</ul>”,
‘first_tag_open’ => ‘<li>’,
‘first_tag_close’ => ‘</li>’,
‘last_tag_open’ => ‘<li>’,
‘last_tag_close’ => ‘</li>’,
‘next_tag_open’ => ‘<li>’,
‘next_tag_close’ => ‘</li>’,
‘prev_tag_open’ => ‘<li>’,
‘prev_tag_close’ => ‘</li>’,
‘num_tag_open’ => ‘<li>’,
‘num_tag_close’ => ‘</li>’,
‘cur_tag_open’ => “<li class=’active’><a>”,
‘cur_tag_close’ => ‘</a></li>’,
];

$this->pagination->initialize($config);

$data=$this->Shade_model->shade_data($config[‘per_page’],$this->uri->segment(3));
$this->load->view(‘admin/shade_view’,[‘types’=>$data]);
}

public function add_shade()
{
$this->load->helper(‘form’); // autoload
$this->load->view(‘admin/add_shade_view’);
}

public function store_shade(){

$this->load->library(‘form_validation’);
$this->form_validation->set_error_delimiters(‘<p class=”text-danger”>’,'</p>’);
if($this->form_validation->run(‘shade’)){ // if validation true
$data=$this->input->post();
$this->load->model(‘Shade_model’);
if($this->Shade_model->add_shade($data)){
$this->session->set_flashdata(‘error’,’Shade save successfully’);
$this->session->set_flashdata(‘error-class’,’alert-success’);
}else{
$this->session->set_flashdata(‘error’,’Shade dose not save, Please try again!!!’);
$this->session->set_flashdata(‘error-class’,’alert-danger’);
}
return redirect(‘shade/shade_list’);
}else{
$this->add_shade();
}
}

public function edit_shade_view($shade_id){

$this->load->model(‘Shade_model’,’shade’);
$shade = $this->shade->find_shade($shade_id);
//print_r($shade);
$this->load->view(‘admin/edit_shade_view’,[‘shade’=>$shade]);
}

public function update_shade($shade_id)
{
$this->form_validation->set_error_delimiters(‘<p class=”text-danger”>’,'</p>’);
if($this->form_validation->run(‘shade’)){ // if validation true
$data=$this->input->post();
$this->load->model(‘Shade_model’,’shade’);
if($this->shade->update_shade($shade_id,$data)){
$this->session->set_flashdata(‘error’,’Shade update successfully’);
$this->session->set_flashdata(‘error-class’,’alert-success’);
}else{
$this->session->set_flashdata(‘error’,’Shade dose not update, Please try again!!!’);
$this->session->set_flashdata(‘error-class’,’alert-danger’);
}
return redirect(‘shade/shade_list’);
}else{
$this->edit_shade_view($shade_id);
}
}

public function delete_shade($shade_id)
{
$this->load->model(‘Shade_model’,’shade’);
if($this->shade->delete_shade($shade_id)){
$this->session->set_flashdata(‘error’,’Shade delete successfully’);
$this->session->set_flashdata(‘error-class’,’alert-success’);
}else{
$this->session->set_flashdata(‘error’,’Shade dose not delete, Please try again!!!’);
$this->session->set_flashdata(‘error-class’,’alert-danger’);
}
return redirect(‘shade/shade_list’);
}
}


Step 4)  Make Model :

Make Model file for shade. Code Given below just copy and save file in model folder and give name Shade_model.php

<?php
class Shade_model extends CI_Model{

public function all_shade_data(){

$data=$this->db
->select([‘shade_id’,’shade_name’])
->from(‘shades’)
->order_by(‘shade_name’,’ASC’)
->get();
return $data->result_array();
}
public function shade_data($limit,$offset){

$data=$this->db
->select([‘shade_id’,’shade_name’])
->from(‘shades’)
->limit($limit,$offset)
->order_by(‘shade_name’,’ASC’)
->get();
return $data->result();
}

public function num_rows(){

$data=$this->db
->select([‘shade_id’,’shade_name’])
->from(‘shades’)
->get();
return $data->num_rows();
}

public function add_shade($data){
return $this->db->insert(‘shades’,[‘shade_name’=>$data[‘shade_name’]]);
}

public function find_shade($shade_id)
{
//exit($ac_type_id);
$q = $this->db->select([‘shade_id’,’shade_name’])
->where(‘shade_id’, $shade_id)
->order_by(‘shade_name’,’ASC’)
->get(‘shades’);

return $q->row();
}

public function update_shade($shade_id,$data)
{
return $this->db
->where(‘shade_id’,$shade_id)
->update(‘shades’,[‘shade_name’=>$data[“shade_name”]]);

}

public function delete_shade($shade_id)
{
return $this->db
->where(‘shade_id’,$shade_id)
->delete(‘shades’);

}
}
?>


Step 5)  Show inserted data View in the table :

Make View file for shade. Code Given below just copy and save file in view folder and give name shade_view.php

<div id=”page-wrapper”>
<div class=”row”>
<div class=”col-lg-12″>
<h1 class=”page-header”>Shade</h1>
</div>
<!– /.col-lg-12 –>
</div>
<!– /.row –>
<div class=”row”>
<div class=”col-lg-12″>
<?php if($error=$this->session->flashdata(‘error’)):
$errorClass=$this->session->flashdata(‘error-class’);
?>
<div class=”alert <?=$errorClass?> alert-dismissable”>
<button type=”button” class=”close” data-dismiss=”alert” aria-hidden=”true”>×</button>
<?php print_r($error); ?>
</div>
<?php endif; ?>
</div>
<div class=”col-lg-12″>
<div class=”panel panel-default”>
<div class=”panel-heading”>
<a href=”<?= base_url(‘shade/add_shade’);?>” class=”btn btn-outline btn-primary ” >Add New</a>
</div>
<!– /.panel-heading –>
<div class=”panel-body”>
<table width=”100%” class=”table table-striped table-bordered table-hover” id=”dataTables-example”>
<thead>
<tr>
<th>No</th>
<th>Shade</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if(count($types)):
$count=$this->uri->segment(3);
foreach($types as $data):
?>
<tr class=”odd gradeX”>
<td><?= ++$count; ?></td>
<td><?= $data->shade_name ?></td>
<td class=”center”>
<a href=”<?= base_url(‘shade/edit_shade_view/’.$data->shade_id);?>” class=”btn btn-outline btn-info”>Edit</a>
<a href=”<?= base_url(‘shade/delete_shade/’.$data->shade_id);?>” class=”btn btn-outline btn-danger”>Delete</a>
</td>
</tr>
<?php
endforeach;
else:
?>
<tr class=”odd gradeX”>
<td colspan=”3″ style=”text-align:center”><b>No records found!!!</b></td>
</tr>
<?php
endif;
?>
</table>
<?= $this->pagination->create_links(); ?>
</div>
<!– /.panel-body –>
</div>
<!– /.panel –>
</div>
<!– /.col-lg-12 –>
</div>
<!– /.row –>

</div>
<!– /#page-wrapper –>


Step 6)  Edit inserted Data :

Make View file for edit shade. Code Given below just copy and save file in view folder and give name edit_shade_view.php

<div id=”page-wrapper”>
<div class=”row”>
<div class=”col-lg-12″>
<h1 class=”page-header”>Shade</h1>
</div>
<!– /.col-lg-12 –>
</div>
<!– /.row –>
<div class=”row”>
<div class=”col-lg-12″>
<div class=”panel panel-default”>
<div class=”panel-heading”>
Edit shade
</div>
<div class=”panel-body”>
<div class=”row”>
<div class=”col-lg-6″>
<?php if($error=$this->session->flashdata(‘error’)):
$errorClass=$this->session->flashdata(‘error-class’);
?>
<div class=”alert <?=$errorClass?> alert-dismissable”>
<button type=”button” class=”close” data-dismiss=”alert” aria-hidden=”true”>×</button>
<?php print_r($error); ?>
</div>
<?php endif; ?>
<?php echo form_open(“shade/update_shade/{$shade->shade_id}”); ?>
<div class=”form-group”>
<label>Shade Name</label>
<?php echo form_input([‘name’=>’shade_name’,’class’=>’form-control’,’placeholder’=>’Enter shade name’,’autofocus’=>’autofocus’,’value’=>set_value(‘cformname’,$shade->shade_name)]);?>
<?php
echo form_error(‘shade_name’) ;
?>
</div>
<?php echo form_submit([‘name’=>’save’,’value’=>’Save’,’class’=>’btn btn-primary’]); ?>
<a href=”<?= base_url(‘shade/shade_list’);?>” class=”btn btn-default”>Back</a>
<?= form_close();?>
</div>
</div>
<!– /.row (nested) –>
</div>
<!– /.panel-body –>
</div>
<!– /.panel –>
</div>
<!– /.col-lg-12 –>
</div>
<!– /.row –>

</div>
<!– /#page-wrapper –>

 

 

Codeigniter Session

Codeigniter Session

#1 Step Set Library in Controller :

 $this->load->library(session);

Add above code in your controller method that enable to user session in your controller model and view file.

#2 Step Save value in session :

 $this->session->set_userdata(‘add_session_name_here‘,’add_session_value_here‘); 

 Set value in session using set_userdata() function, here you need to two thing required #2.1 name of session (as per your use) #2.2 Value of session (what data you want to store).

#3 Step GET value From session :

 $this->session->userdata(‘session_name_here‘); 

Get value from session using userdata() function, here you need only session name.

 

Create a MySQL Database

Create a MySQL Database

MySql database contains a number of databases.  You can create a database as per your uses, simply using  CREATE DATABASE statement

<?php
$con=mysqli_connect(“localhost”,”root”,””); // database local connection

// Connection
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}

// Create database
$sql = “CREATE DATABASE my_db”; // Query for create database
if (mysqli_query($conn, $sql))
{
echo “Database created successfully”;
}
else
{
echo “Error creating database: ” . mysqli_error($conn);
}

mysqli_close($conn); // Close database connection
?>

Next Mysql Query

 

Data Types In PHP

PHP DATA TYPE

Data type simply means store different type of data and its uses. In PHP there are 8 data types as follows.

  1. String
  2. Integer
  3. Float
  4. Boolean
  5. Null
  6. Array
  7. Object
  8. Resource

#1 PHP String 

String means group or sequence of characters. Ex  Hello World! 

You can store string inside PHP variable using single quotation or  double quotation.

<?php

echo $name=”Virat”;

echo $surname=’Kohli’;   

?> 

#2 PHP Integer

In this data type variable hold number without a decimal and its range is fixed between  -2,147,483,648 and 2,147,483,647.

Here is some rule of Integer

  • One digit required
  • Number is positive or negative
  • No decimal point

<?php

$a=10;

$b=20;

echo $sum=$a+$b; // output : 30

?>

Tip

For an integer, you have don’t want to define this is an integer value you can use single quotation or double quotation mark PHP automatically get what datatype you want to use

#3 Float

The float is number with a decimal point like 10.50.  In float value required decimal point and some number after point

<?php

var_dump(10.50); // Output : float(10.50)

?>

#4 Boolean

The boolean mean true or false. other mean 1 or 0.

Boolean simply use testing condition. if the condition is true then do this else do this

 

mysqli_query()

mysqli_query()

Using this function you can run all database query like INSERT, UPDATE, DELETE data into the table.

<?php
$con=mysqli_connect(“localhost”,”root”,””,”my_db”); // database local connection
// Connection
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}

//  Queries
mysqli_query($con,”SELECT * FROM user”); // Select data from table
mysqli_query($con,”INSERT INTO user(FirstName,LastName,Age)
VALUES (‘jay’,’amin’,33)”); // insert data into table
mysqli_query($con,”DELETE FROM user where FirstName=’jay'”); // Delete data from table

mysqli_close($con); // Close database connection
?>

var_dump()

var_dump()

This is a PHP inbuild function that returns us a value and datatype and length of value or variable.

<?php // Exampal
$var_name1=678;
$var_name2=”a678″;
$var_name3=”678″;
$var_name4=”sometext”;
$var_name5=698.99;
$var_name6=+125689.66;
echo var_dump($var_name1).”<br  />”;
echo var_dump($var_name2).”<br  />”;
echo var_dump($var_name3).”<br  />”;
echo var_dump($var_name4).”<br  />”;
echo var_dump($var_name5).”<br  />”;
echo var_dump($var_name6).”<br  />”;
?>

Output : 
int(678)
string(4) “a678”
string(3) “678”
string(8) “sometext”
float(698.99)
float(125689.66)

Tip

You can use for checking what type of data you recive. Or checking structured information about the object / variable

 

Connection with MySql database : mysqli_connect()

MYSQLI mysqli_connect()

MySqli is database driver for connection with MySQL database.

Connect MySQL database using PHP script  

<?php

mysqli_connect(hostname‘,’username‘,’password‘,’database_name);

?>

Here mysqli_connect is inbuild function of php for connection with MySql database.

In this function, you required four parameters as shown in above script.

  • hostname: your database hosting name if in your computer then write localhost for local database use else writes database provider name.
  • username: your database username. if in the local server then write root.
  • password: Your database password. if in the local server then leave is blank. As shown in blow script
  • database_name: name of your database.

<?php

// Local connection script

$connection=mysql_connect(‘localhost’,’root’,”,’test_db’);

if(mysqli_connect_errno()){    //

echo “Error : Database could not connect : “. mysqli_connect_error(); // if databse not connected then show error

}

?>

Next Create Database 

Concatenation Operators

<?php

$firstName=”Virat”;

$leatName=” Kohali”;

         echo $firstName.” “.$lastName;  // Output : Virat Kohali

?>

Here in this PHP code, you can see two red color dot symbol, we call as concatenation operators. Using this concatenation operator we can print the two variable value in one echo statement as shown in the code.

Concatenation Assignment

<?php

$message=“Hello,”;

$message.=” Learning PHP code is to easy”;

echo $message; // Output : Hello, Learning PHP code is to easy

?>

Using concatenation assignment you can append the variable value, show as above code. In this code first $message with only equal sing and second with concatenation operator

Concatenation Tip 

  • Mostly use for combine and append string in variable
  • You can use HTML code also

Next var_dump()

Echo & Print

<?php

            echo “Hello”;

           $myName=”Your name here”;

           echo $myName;

           print $myName;

?>

In PHP if you want to print the value of a variable or other string then you have to use echo keyword with variable ($myName) or your string (Hello) inside of dual quotation (“Hello“) and last add semicolon (;

Echo Tip

  • You can also use single quotation (‘Hello‘)
  • Direct writing echo before a variable name like  <?php echo $myName; ?>
  • You can also use <?= $myName ?>
  • You can also use <?php print “Some String here “; ?>
  • You can aslo use html tag in side print and echo <?php echo “<h1>Hello !!!</h1>” ?>

Next Concatenation Operators

 

 

 

PHP Variable

PHP variable

Variable is simply storing some value inside and use in the program.
In PHP, you can make variable using $ sing.
Example $a=”Hello World!”; $x=10;
In variable you can store Strings and numbers.
You can assign a value using = Sing (the left side you variable name = right side your value ).

Variable Tip

Make all variable name in the small letter. Example $total=100;, $username=”abdxyz”;
IF variable have two word combination like username then user camel case
Example $userName=”Hello World!”; $firstName=”jignesh”; In camel case second word first letter is capital
Make all variable name descriptive. Example store total with GST then its $totalWithGst

Variable Trick

$total=100;, $a=10;
Assign string value using signal quotation and dual quotation $userName=”Hello World!”; $firstName=’jignesh’;