Tuesday, 10 March 2015

PAGINATION_IN_CODEIGNITER

(1)write code  for "countries.php"  save into models :

<?php

class Countries extends CI_Model
{
    public function __construct() {
        parent::__construct();
    }

    public function record_count()
{

$this->load->database();

     return $this->db->count_all("contact_info"); //where contact_info is a table name

    }

    public function fetch_countries($limit, $start)
{
        $this->db->limit($limit, $start);

        $query = $this->db->get("contact_info");

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }
}

?>

(2)write code for  example1.php    save into views folder:


<html>
<body>
 <div id="container">
  <h1>Countries</h1>
  <div id="body">
<?php
foreach($results as $data) {
    echo $data->name;
echo $data->email;
}
?>
   <p><?php echo $links; ?></p>

  </div>

  <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>

 </div>
</body>
</html>

(3)write code for   "welcome.php"  & save it into controllers folder:



<?php
class Welcome extends CI_Controller
{
    public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
        $this->load->model("Countries");
        $this->load->library("pagination");
    }

    public function example1() {
        $config = array();

$config["base_url"] = base_url() . "index.php/welcome/example1";

        //$config["<span class="s24bzc094h8" id="s24bzc094h8_5" style="height: 16px;">base</span>_url"] = base_url() . "welcome/example1"];
        $config["total_rows"] = $this->Countries->record_count();
        $config["per_page"] = 2;
        $config["uri_segment"] = 3;

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

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data["results"] = $this->Countries->
            fetch_countries($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();

        $this->load->view("example1", $data);
    }
}


?>

(4) to run type in browser:

http://localhost/ci/index.php/welcome/example1

PAGINATION IN CODEIGNITER



(1)create table contact_info


CREATE TABLE contact_info(
id  int(11) NOT NULL AUTO_INCREMENT,
name  varchar(255) NOT NULL,
email  varchar(255) NOT NULL,
mobile_number  int(11) NOT NULL,
country  varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);



(2)then write code for "pagination_model.php" :


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

class Pagination_Model extends CI_Model

{
function __construct() {
parent::__construct();
}
// Count all record of table "contact_info" in database.
public function record_count() {

$this->load->database();
return $this->db->count_all("contact_info");
}

// Fetch data according to per_page limit.

public function fetch_data($limit, $id) {
$this->db->limit($limit);
$this->db->where('id', $id);
$query = $this->db->get("contact_info");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}

return $data;
}
return false;
}
}


(3)then write code for "pagination_view.php" :

<html>

<head>

<title>Codelgniter pagination</title>

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">

<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="main">
<div id="content">
<h3 id='form_head'>Codelgniter Pagination Example </h3><br/>
<hr>
<div id="form_input">
<?php

// Show data
foreach ($results as $data) {
echo "<label> Id </label>" . "<div class='input_text'>" . $data->id . "</div>"
. "<label> Name</label> " . "<div class='input_name'>" . $data->name . "</div>"
. "<label> Email </label>" . "<div class='input_email'>" . $data->email . "</div>"
. "<label> Mobile No </label>" . "<div class='input_num'>" . $data->mobile_number . "</div>"
. "<label> Country </label> " . "<div class='input_country'>" . $data->country . "</div>";
}
?>
</div>
<div id="pagination">
<ul class="tsc_pagination">

<!-- Show pagination links -->
<?php foreach ($links as $link) {
echo "<li>". $link."</li>";
} ?>
</div>
</div>
</div>
</body>
</html>

(4)then write code for  "pagination_controller.php":



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

class Pagination_Controller extends CI_Controller {

// Load libraries in Constructor.
function __construct() {
parent::__construct();
$this->load->model('pagination_model');
$this->load->library('pagination');
}

// Set array for PAGINATION LIBRARY, and show view data according to page.

public function contact_info(){

$this->load->database();

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

$config = array();




$config["base_url"] = base_url() . "index.php/pagination_controller/contact_info";

$total_row = $this->pagination_model->record_count();

$config["total_rows"] = $total_row;

$config["per_page"] = 1;
$config['use_page_numbers'] = TRUE;
$config['num_links'] = $total_row;
$config['cur_tag_open'] = '&nbsp;<a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';

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

if($this->uri->segment(3))
{
$page = ($this->uri->segment(3)) ;
}
else
{
$page = 1;
}
$data["results"] = $this->pagination_model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode('&nbsp;',$str_links );

// View data according to array.
$this->load->view("pagination_view", $data);
}
}
?>

(5)To run file:

http://localhost/ci/index.php/pagination_controller/contact_info




note:

create  css folder into your root directory.

following is css code for:

body {
font-family: 'Raleway', sans-serif;
}
.main
{
width: 1015px;
position: absolute;
top: 10%;
left: 20%;
}
#form_head
{
text-align: center;
background-color: #61CAFA;
height: 66px;
margin: 0 0 -29px 0;
padding-top: 35px;
border-radius: 8px 8px 0 0;
color: rgb(255, 255, 255);
}
#content {
position: absolute;
width: 450px;
height: 390px;
border: 2px solid gray;
border-radius: 10px;
}
#form_input
{
margin-left: 110px;
margin-top: 30px;
}
label
{
margin-right: 6px;
font-weight: bold;
}
#pagination{
margin: 40 40 0;
}
.input_text {
display: inline;
margin: 100px;
}
.input_name {
display: inline;
margin: 65px;
}
.input_email {
display: inline;
margin-left: 73px;
}
.input_num {
display: inline;
margin: 36px;
}
.input_country {
display: inline;
margin: 53px;
}
ul.tsc_pagination li a
{
border:solid 1px;
border-radius:3px;
-moz-border-radius:3px;
-webkit-border-radius:3px;
padding:6px 9px 6px 9px;
}
ul.tsc_pagination li
{
padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current
{
color:#FFFFFF;
box-shadow:0px 1px #EDEDED;
-moz-box-shadow:0px 1px #EDEDED;
-webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination
{
margin:4px 0;
padding:0px;
height:100%;
overflow:hidden;
font:12px 'Tahoma';
list-style-type:none;
}
ul.tsc_pagination li
{
float:left;
margin:0px;
padding:0px;
margin-left:5px;
}
ul.tsc_pagination li a
{
color:black;
display:block;
text-decoration:none;
padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img
{
border:none;
}
ul.tsc_pagination li a
{
color:#0A7EC5;
border-color:#8DC5E6;
background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current
{
text-shadow:0px 1px #388DBE;
border-color:#3390CA;
background:#58B0E7;
background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}









How to Update value from a form to database in codeigniter Framework?



(1)create table  'tbl_name':

create table tbl_name

(id int(5) primary key auto_increment,

f1   varchar(200),

f2  varchar(200),

f3  varchar(200));


(2) write code for   'upform.php' save it into views folder of codeigniter:


<form action="<?php echo site_url('up/upd'); ?>"  method=post>

Field 1 <input type = ‘text’ name='f1'><br>

Field 2 <input type = ‘text’ name='f2'><br>

Field 3 <input type = ‘text’ name='f3'><br>

<input type="submit"  name="submit"  value="submit">

</form>


(3)write code for  'update_model.php'  save it into models folder of codeigniter:

<?php

class update_model extends CI_Model

{


function __construct()
        {
            parent::__construct();
        }

       
public function update($data) {
  $f1 = $data['f1'];
  unset($data['f1']);
  $this->db->where('f1', $f1);
  $this->db->update('tbl_name' ,$data);
  return true;
}

}

?>

(4)write code for 'up.php'  save it into  models folder of   controllers:


<?php

class up extends CI_Controller

{

function __construct()

{

parent::__construct();

$db = $this->load->database();

}
function index()

{

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

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




}

function upd()

{




$this->load->database();

$this->load->model('update_model');




                      
                      
                      
                      
                       $data = array(
          
           'f1' => $this->input->post('f1'),
           'f2' => $this->input->post('f2'),
           'f3' => $this->input->post('f3')
          
        );
                      
$this->update_model->update($data);



}

}

(5)Then  opend browser   &  type    'http://localhost/ci/index.php/up'


(where ci  is   codeigniter )








How to insert value FORM to DATABASE using CodeIgniter?

(1)create table  'tbl_name':

create table tbl_name

(id int(5) primary key auto_increment,

f1   varchar(200),

f2  varchar(200),

f3  varchar(200));


(2) write code for   'form.php' save it into views folder of codeigniter:


<form action="<?php echo site_url('site/insert'); ?>"  method=post>

Field 1 <input type = ‘text’  name='f1'><br>

Field 2 <input type = ‘text’  name='f2'><br>

Field 3 <input type = ‘text’  name='f3'><br>

<input type="submit"  name="submit"  value="submit">

</form>


(3)write code for  'site_model.php'  save it into models folder of codeigniter:

<?php

class site_model extends CI_Model

{


function __construct()
        {
            parent::__construct();
        }

public function insertdata($data)

{

$this->load->database();



$this->db->insert('tbl_name', $data);

}

}

?>

(4)write code for 'site.php'  save it into  models folder of   controllers:


<?php

class site extends CI_Controller

{

function __construct()

{

parent::__construct();

$db = $this->load->database();

}
function index()

{

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

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




}

function insert()

{




$this->load->database();

$this->load->model('site_model');




                      
                      
                      
                      
                       $data = array(
          
           'f1' => $this->input->post('f1'),
           'f2' => $this->input->post('f2'),
           'f3' => $this->input->post('f3')
          
        );
                      
$this->site_model->insertdata($data);


}

}


(5)then opend browser  & type    'http://localhost/ci/index.php/site'

(where ci  is  codeigniter )








Monday, 9 March 2015

How to display data from a table using CodeIgniter?

(1)write code for class Emp_model & save as  Emp_model.php


<?php

class Emp_model extends CI_Model

{

  function emp_getall()

  {
       $this->load->database();
       $query=$this->db->get('items');//items is a table in the database
       return $query->result();
  }

}


?>


(2)wrtie code for class emp_viewall & save as emp_viewall.php:


<?php

foreach($query as $row)
{
 
  print $row->name;
 
 
  print "<br>";
 
}

?>

(3)write code for class emp & save as emp.php:

<?php
class emp extends CI_Controller
{
 
  function GetAll()
  {
     $this->load->model('emp_model');

       $data['query']=$this->emp_model->emp_getall();

       $this->load->view('emp_viewall',$data);
  }
}

?>





(4)Run code  by typing  url on browser:

"http://localhost/ci/index.php/emp/getall"

how to insert data into mysql using CodeIgniter ?

(1)first go to  application/config folder


and change your connection values:

$db['default']['hostname'] = 'localhost';


$db['default']['username'] = 'root';


$db['default']['password'] = '';


$db['default']['database'] = 'code';


$db['default']['dbdriver'] = 'mysql';


(2)create table 'items':

create table  items
(name varchar(200));


(3)write code for model class & save it as  EmployeeModel.php under "Model "   folder:


<?php

class EmployeeModel extends CI_Model  {



function insertEmployee($employee){
$this->db->insert('items', $employee); // insert data into `trn_employee`
//table
}
}
?>

(4)write code for controller class & save it as  Employee.php under "controllers"   folder :

 <?php

class Employee extends CI_controller {



function index()

{



$this->load->database();



$this->load->model('EmployeeModel');

// create data
$employee = array(

'name' =>"Sunil",

);

// table column name should be same as data object key name

$this->EmployeeModel->insertEmployee($employee); // call the employee model


}


}


?>

CodeIgniter Tutorial for creating Header ,Footer & display content..

(1)Download codeigniter from "http://www.codeigniter.com/download"


(2) create folder ci under path "c:/wamp/www"


(3) then  extract  zip  file of  CodeIgniter-2.2.1 into "ci" folder.

 (means into following path=
"C:/wamp/www/ci")


(4)then go to browser & type

"localhost/ci/" (note: you will see welcome message )


(5)now  understand  Codeigniter  sturcture:

It contains three  main folder under "application" folder:


(a)controllers (handles all incoming Http requests,passes data to the views).


(b)views(Renders the Html output).


(c)Models(Encapsulate  Business Logic,such as Interaction with database).


(6)now opend notepad type following code:
<h1> this is header </h1>

save file name as header.php   & save this file under "views" folder.

(7) type code:
<h1>this is content </h1>





save file name as content.php & save this file under "views" folder.

(8) type code:


h1> this is footer </h1>

save file name as footer.php & save this file under "views" folder.


(9) now wirte following code :
<?php

class Hello extends CI_controller

{

public function one()

{


echo "this is one";


}
public function two()
{

$this->load->view('header.php');

$this->load->view('content.php');

$this->load->view('footer.php');

}

}



save this file as hello.php  & save this file under "controllers" folder.





(10) Now  open  browser & to run one function of hello class

 type following  url:"Localhost/index.php/hello/one


output: this is one


(11)Now  open  browser & to run two function of hello class

 type following  url:"Localhost/index.php/hello/two


output:

this is header
this is content
this is footer















Saturday, 7 March 2015

preg_match — Perform a regular expression match for email,name ,URL

see code below for example.php:


Read explanation of above used preg_match():

PHP - Validate E-mail

The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:

$email = test_input($_POST["email"]);if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {  $emailErr = "Invalid email format"; }








PHP - Validate URL

The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:

$website = test_input($_POST["website"]);if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {  $websiteErr = "Invalid URL"; }






PHP - Validate Name

The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:

$name = test_input($_POST["name"]);if (!preg_match("/^[a-zA-Z ]*$/",$name)) {  $nameErr = "Only letters and white space allowed"; }



//function code:

function test_input($data) {   $data = trim($data);   $data = stripslashes($data);   $data = htmlspecialchars($data);   return $data;}


PHP script for Contact form validation

(1)write code for "contactform.php  file":

<?php include 'validation.php';?>

<!DOCTYPE HTML>

<html>
<head>
<title>PHP Contact Form with Validation</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Contact Form with Validation</h2>
<form method="post" action="contactform.php">
<label>Name :</label>
<input class="input" type="text" name="name" value="">
<span class="error"><?php echo $nameError;?></span>
<label>Email :</label>
<input class="input" type="text" name="email" value="">
<span class="error"><?php echo $emailError;?></span>
<label>Purpose :</label>
<input class="input" type="text" name="purpose" value="">
<span class="error"><?php echo $purposeError;?></span>
<label>Message :</label>
<textarea name="message" val=""></textarea>
<span class="error"><?php echo $messageError;?></span>
<input class="submit" type="submit" name="submit" value="Submit">
<span class="success"><?php echo $successMessage;?></span>
</form>
</div>
</div>
</body>
</html>


(2) write code for  "validation.php"  file :


<?php // Initialize variables to null.
$name =""; // Sender Name
$email =""; // Sender's email ID
$purpose =""; // Subject of mail
$message =""; // Sender's Message
$nameError ="";
$emailError ="";
$purposeError ="";
$messageError ="";
$successMessage =""; // On submitting form below function will execute.

function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['submit'])) { // Checking null values in message.
if (empty($_POST["name"])){
$nameError = "Name is required";
}
else
 {
$name = test_input($_POST["name"]); // check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
} // Checking null values in the message.
if (empty($_POST["email"]))
{
$emailError = "Email is required";
}
else
 {
$email = test_input($_POST["email"]);
} // Checking null values in message.
if (empty($_POST["purpose"]))
{
$purposeError = "Purpose is required";
}
else
{
$purpose = test_input($_POST["purpose"]);
} // Checking null values in message.
if (empty($_POST["message"]))
{
$messageError = "Message is required";
}
else
 {
$message = test_input($_POST["message"]);
} // Checking null values in the message.
if( !($name=='') && !($email=='') && !($purpose=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "FormGet.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Purpose: $purpose
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Here is some information about $name.
Name: $name
E-mail: $email
Purpose: $purpose
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("receiver_mail_id@xyz.com", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{ $emailError = "Invalid Email";
 }
 }
} // Function for filtering input values. function test_input($data)

?>



Wednesday, 4 March 2015

Difference between $ and $$ in php

<?php

$test = "hello world";

$a = "test";



echo $$a;


?>

output :

hello world

note: $a  represents a variable
and $$a  represents a variable  with content (for example $test content it holds)




How To Submit a form without a submit button?

simple just use following code save it as  example.html:

<form name="myform" action="handle-data.php">
Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
  document.myform.submit();
}
</script>

PHP And Ajax (with MYsql database)



(1) create  databse ajax & into that create table ajax_example:

CREATE TABLE `ajax_example` (
  `name` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `sex` varchar(1) NOT NULL,
  `wpm` int(11) NOT NULL,
  PRIMARY KEY  (`name`)
);

(2)now insert the data into table:


INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);


(3)write code for ajax.html:

<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "?age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

(4)write code for php file  "ajax-example.php":



<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "ajax";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>


Monday, 2 March 2015

PHP Script for Sending email

<?php

   $to = "omchandmaurya1@gmail.com";
  
   $subject = "This is subject";
  
   $message = "This is simple text message.";
  
   $header = "From:omnetworkom@gmail.com \r\n";
  
   $retval = mail ($to,$subject,$message,$header);
  
   if( $retval == true ) 
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }

?>