Tuesday, 10 March 2015

Display image from a folder in Codeigniter

(1)write  code for  "displayimage.php"  fiel & save into views folder:

<?php

$this->load->helper('directory'); //load directory helper

$dir = "uploads/"; // Your Path to folder

$map = directory_map($dir); /* This function reads the directory path specified in the first parameter and builds an array representation of it and all its contained files. */


foreach ($map as $k)

{?>
     <img src="<?php echo base_url($dir)."/".$k;?>"  height="200"  width="200"   alt="">
  
<?php }
         
?>




(2)write code for upload_controller.php file  & save inot controllers:


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


class  Upload_Controller extends CI_Controller

{

public function __construct()

{
parent::__construct();

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

public function displayimage()

{

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



}


}


?>


(3)to run  it open browser & type following code:

  "localhost/ci/index.php/upload_controller/displayimage"

CodeIgniter_ Image _and _File _Upload

(1)first create "uploads" folder into root directory of codeigniter.


(2)write code for  "file_view.php" file & save it to  views folder:

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php $this->load->helper('form'); ?>
<?php echo $error;?> <!-- Error Message will show up here -->
<?php echo form_open_multipart('index.php/upload_controller/do_upload');?>
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</body>
</html>


(3)write code for "upload_controller.php" file & save it to  controllers folder:



<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload_Controller extends CI_Controller {
public function __construct() {
parent::__construct();

$this->load->helper('url');
}
public function file_view(){

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

$this->load->view('file_view', array('error' => ' ' ));
}
public function do_upload(){
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "500048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "10000",
'max_width' => "102400"
);
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success',$data);
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('file_view', $error);
}
}
}
?>


(4)write code for  file   "upload_success.php"  & save it views folder:

<html>
<head>
<title>Upload File Specification</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<!-- Uploaded file specification will show up here -->
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('index.php/upload_controller/file_view', 'Upload Another File!'); ?></p>
</body>
</html>


(5)To run it open browser   &    type following:


"http://localhost/ci/index.php/upload_controller/file_view"




Login page_Registration page_in _Codeigniter

(1)
create table user_login
(

id  int primary key auto_increment,

user_name    varchar(200),

user_email    varchar(200),

user_password   varchar(200),

name            varchar(200));


(2)write code for    "login_database.php"   save this into models folder:


<?php

Class Login_Database extends CI_Model

{

// Insert registration data in database
public function registration_insert($data)

{

$this->load->database();

// Query to check whether username already exist or not

$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {

// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}

// Read data using username and password
public function login($data) {

$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}

// Read data from database to show data in admin page
public function read_user_information($sess_array) {

$condition = "user_name =" . "'" . $sess_array['username'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}

}

?>

(3)wrtie code for  "login_form.php" file  & save this into views folder:





<html>
<head>
<title>Login Form</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>
<?php
if (isset($logout_message)) {
echo "<div class='message'>";
echo $logout_message;
echo "</div>";
}
?>
<?php
if (isset($message_display)) {
echo "<div class='message'>";
echo $message_display;
echo "</div>";
}
?>
<div id="main">
<div id="login">
<h2>Login Form</h2>
<?php echo form_open('index.php/user_authentication/user_login_process'); ?>
<?php
echo "<div class='error_msg'>";
if (isset($error_message)) {
echo $error_message;
}
echo validation_errors();
echo "</div>";
?>
<label>UserName :</label>
<input type="text" name="username" id="name" placeholder="username"/>
<label>Password :</label>
<input type="password" name="password" id="password" placeholder="**********"/>
<input type="submit" value=" Login " name="submit"/>
<a href="user_registration_show">To SignUp Click Here</a>
<?php echo form_close(); ?>
</div>
</div>
</body>
</html>

(4)write code for "registration_form.php"  file & save into views folder:

<html>
<head>
<title>Registration Form</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 id="main">
<div id="login">
<h2>Registration Form</h2>
<?php
echo "<div class='error_msg'>";
echo validation_errors();
echo "</div>";
echo form_open('index.php/user_authentication/new_user_registration');
echo form_label('Name : ');
echo form_input('name');
echo form_label('Create Username : ');
echo form_input('username');
echo "<div class='error_msg'>";
if (isset($message_display)) {
echo $message_display;
}
echo "</div>";
echo form_label('Email : ');
$data = array(
'type' => 'email',
'name' => 'email_value'
);
echo form_input($data);
echo form_label('Password : ');
echo form_password('password');
echo form_submit('submit', 'Sign Up');
echo form_close();
?>
</div>
</div>
</body>
</html>


(5)write code for "admin_page.php" file:

<html>
<head>
<title>Admin Page</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 id="profile">
<?php
echo "Hello <b id='welcome'><i>" . $name . "</i> !</b>";
echo "Welcome to Admin Page";
echo "Your Username is " . $username;
echo "Your Email is " . $email;
echo "Your Password is " . $password;
?>
<b id="logout"><a href="logout">Logout</a></b>
</div>
</body>
</html>



(6)write code for  user_authentication.php  file & save it to controllers folder:



<?php

session_start(); //we need to start session in order to access it through CI

Class User_Authentication extends CI_Controller {

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

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

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

$this->load->helper('url');
// Load form helper library
$this->load->helper('form');

// Load form validation library
$this->load->library('form_validation');

// Load session library
$this->load->library('session');

// Load database
$this->load->database();
$this->load->model('login_database');

}

// Show login page
public function user_login_show() {
$this->load->view('login_form');
}

// Show registration page
public function user_registration_show() {
$this->load->view('registration_form');
}

// Validate and store registration data in database
public function new_user_registration() {

// Check validation for user input in SignUp form
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('registration_form');
} else {
$data = array(
'name' => $this->input->post('name'),
'user_name' => $this->input->post('username'),
'user_email' => $this->input->post('email_value'),
'user_password' => $this->input->post('password')
);
$result = $this->login_database->registration_insert($data) ;
if ($result == TRUE) {
$data['message_display'] = 'Registration Successfully !';
$this->load->view('login_form', $data);
} else {
$data['message_display'] = 'Username already exist!';
$this->load->view('registration_form', $data);
}
}
}

// Check for user login process
public function user_login_process() {

$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);

// Add user data in session
$this->session->set_userdata('logged_in', $sess_array);
$result = $this->login_database->read_user_information($sess_array);
if($result != false){
$data = array(
'name' =>$result[0]->name,
'username' =>$result[0]->user_name,
'email' =>$result[0]->user_email,
'password' =>$result[0]->user_password
);
$this->load->view('admin_page', $data);
}
}else{
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}

// Logout from admin page
public function logout() {

// Removing session data
$sess_array = array(
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('login_form', $data);
}
}

?>






NOTE:



Setting your Key


Your key can be either stored in your application/config/config.php, or you can design your own storage mechanism and pass the key dynamically when encoding/decoding.
To save your key to your application/config/config.php, open the file and set:

$config['encryption_key'] = "YOUR KEY";

Message Length

It's important for you to know that the encoded messages the encryption function generates will be approximately 2.6 times longer than the original message. For example, if you encrypt the string "my super secret data", which is 21 characters in length, you'll end up with an encoded string that is roughly 55 characters (we say "roughly" because the encoded string length increments in 64 bit clusters, so it's not exactly linear). Keep this information in mind when selecting your data storage mechanism. Cookies, for example, can only hold 4K of information.

Initializing the Class

Like most other classes in CodeIgniter, the Encryption class is initialized in your controller using the

$this->load->library function:

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

(7)to run  type in browser:

http://localhost/ci/index.php/user_authentication/user_login_show








(8)css code for   save it into root folder under css folder:


#main{
width:960px;
margin:50px auto;
font-family:raleway;
}

span{
color:red;
}

h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 30px;
}

#login{

width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: 70px;
}

input[type=text],input[type=password], input[type=email]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}

input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}

#profile{
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7;
}

#logout{
float:right;
padding:5px;
border:dashed 1px gray;
margin-top: -168px;
}

a{
text-decoration:none;
color: cornflowerblue;
}

i{
color: cornflowerblue;
}

.error_msg{
color:red;
font-size: 16px;
}

.message{
position: absolute;
font-weight: bold;
font-size: 28px;
color: #6495ED;
left: 262px;
width: 500px;
text-align: center;
}








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)