article

Sunday, August 4, 2013

CakePHP Add,Edit,Delete and Validate

CakePHP Add,Edit,Delete and Validate

Create Database Table
CREATE TABLE `categories` (
  `id` INTEGER(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM

Crate Model app\models\category.php

<?php
class Category extends AppModel {
    var $name = 'Category';
 var $validate = array( //validate
        'name' => array(
            'rule' => 'notEmpty',
            'message' => 'No, no, this field must not be empty!'
        )
    );
}
?>
Create Controller app/controllers/categories_controller.php
<?php
class CategoriesController extends AppController {
 
    var $name = 'Categories';
 
    function index() {
        $this->set('categories', $this->Category->find('all'));
    }
     
    function add() {
        if (!empty($this->data)) {
            if ($this->Category->save($this->data)) {
                $this->Session->setFlash('Your category has been saved.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
 function delete($id) {
        $this->Category->delete($id);
        $this->Session->setFlash('The category with id: '.$id.' has been deleted.');
        $this->redirect(array('action'=>'index'));
    }
 function edit($id = null) {
        $this->Category->id = $id;
        if (empty($this->data)) {
            $this->data = $this->Category->read();
        } else {
            if ($this->Category->save($this->data)) {
                $this->Session->setFlash('Your category has been updated.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}
?>
Create View index app/view/categories/index.ctp
<!-- File: /app/views/categories/index.ctp -->
<h1>Categories</h1>
<?php echo $html->link('Add Category',array('controller' => 'categories', 'action' => 'add')); ?>
 
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Actions</th>
    </tr>
 
    <?php foreach ($categories as $category): ?>
    <tr>
        <td><?php echo $category['Category']['id']; ?></td>
        <td>
            <?php echo $html->link($category['Category']['name'],
array('controller' => 'categories', 'action' => 'edit', $category['Category']['id'])); ?>
        </td>
        <td>
        <?php echo $html->link('Delete', array('action' => 'delete', $category['Category']['id']), null, 'Are you sure?' )?>
        <?php echo $html->link('Edit', array('action'=>'edit', $category['Category']['id']));?>
        </td>
    </tr>
    <?php endforeach; ?>
 
</table>
Create View Edit app/view/categories/edit.ctp
<h1>Edit Category</h1>
<?php
    echo $form->create('Category', array('action' => 'edit'));
    echo $form->input('name');
    echo $form->input('id', array('type'=>'hidden'));
    echo $form->end('Save Category');
?>
Create View add app/view/categories/add.ctp
<h1>Add Category</h1>
<?php
echo $form->create('Category');
echo $form->input('name');
echo $form->end('Save Post');
?>

CakePHP Making a small application

CakePHP Making a small application

Create Database Table

CREATE TABLE `categories` (
  `id` INTEGER(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM
Create Model app\models\category.php 


<?php
class Category extends AppModel {
    var $name = 'Category';
}
?>
Create Controller app\controllers\categories_controller.php
<?php
class CategoriesController extends AppController {
    var $name = 'Categories';
    function index() {
        $this->set('categories', $this->Category->find('all'));
    }
     
    function add() {
        if (!empty($this->data)) {
            if ($this->Category->save($this->data)) {
                $this->Session->setFlash('Your category has been saved.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}
?>
Create View index app\views\categories\index.ctp
<!-- File: /app/views/categories/index.ctp -->
 <?php echo $html->link('Add Category',array('controller' => 'categories', 'action' => 'add')); ?>
<h1>Categories</h1>

<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
    </tr>
 
    <?php foreach ($categories as $category): ?>
    <tr>
        <td><?php echo $category['Category']['id']; ?></td>
        <td>
            <?php echo $html->link($category['Category']['name'],
array('controller' => 'categories', 'action' => 'view', $category['Category']['id'])); ?>
        </td>
    </tr>
    <?php endforeach; ?>
 
</table>
Create View add app\views\categories\add.ctp
<!-- File: /app/views/categories/add.ctp -->   
<h1>Add Category</h1>
<?php
echo $form->create('Category');
echo $form->input('name');
echo $form->end('Save Post');
?>

Saturday, August 3, 2013

Defining and Using Functions in PHP

Defining and Using Functions in PHP 

A function is a self-contained piece of code which carries out a particular task or function. benefit of using functions is that they are reusable


<?php
//Defining a Function
//syntax for defining a function
function addNumbers($num1, $num2) {
    $result = $num1 + $num2;
    return $result;
}
$total = addNumbers(5, 10); 
//echo $total; //result 15

//Organizing Functions
function hello() {
    echo "<h1>HELLO!</h1>";
    echo "<p>Welcome to my web site</p>";
}

function printBreak($text) {
    echo "$text<br>";
}

function addNumbers($num1, $num2) {
     return $num1 + $num2;
}

echo hello();
echo printBreak("This is a line");
echo addNumbers(3.75, 5.645); //9.39536.75

//Accepting a Variable Number of Arguments
function calcAverage() {
    // initialize value to be used in calculation
    $total = 0;       

    // find out how many arguments were given
    $arguments = func_num_args();      

    // loop to process each argument separately
    for ($i = 0; $i < $arguments; $i++) {
        // add the value in the current argument to the total
        $total += func_get_arg($i);
    }

    // after adding all arguments, calculate the average
    $average = $total / $arguments;  

    // return the average
    return $average;
}

// invoke the function with 5 arguments
//echo calcAverage(44, 55, 66, 77, 88); //output 66   

// invoke the function with 8 arguments
echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7); //ouput 36.75

Friday, August 2, 2013

CodeIgniter show record from database

CodeIgniter show record from database

Create Table
CREATE TABLE IF NOT EXISTS `daily` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `name` varchar(64) NOT NULL,
  `amount` double NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
Insert
INSERT INTO `daily` (`id`, `date`, `name`, `amount`) VALUES
(1, '2012-02-21', 'Kenshin', 5000),
(2, '2012-02-21', 'Naruto', 6000),
(3, '2012-02-21', 'Lufy', 7000),
(4, '2012-02-21', 'Zoro', 8000),
(5, '2012-02-21', 'Franky', 9000);

Controller
application\controllers\welcome.php
<?php 
class Welcome extends CI_Controller {

 function index(){ 
  $this->load->library('table');
  $this->load->database(); 
  $data['records']=$this->db->get('daily');
  $header = array('ID', 'Date', 'Name', 'Amount'); 
  $this->table->set_heading($header);
  $this->load->view('welcome/index',$data); 
 }
}
View
views\welcome\index.php
<div id="container">
 <h1>Welcome to CodeIgniter!</h1>
<div id="body">
 <?php echo $this->table->generate($records); ?>
 </div>
</div>

CodeIgniter Form Validation

CodeIgniter Form Validation 

Controller 
application\controllers\welcome.php

<?php
class Welcome extends CI_Controller {
 public function index()
 {
  //Form Validation
  $this->load->helper(array('form', 'url'));
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username', 'required');
  $this->form_validation->set_rules('password', 'Password', 'required');
  $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required');
  //Validation Functions
  //$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');
  //$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
  //$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  //$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
  if ($this->form_validation->run() == FALSE)
  {
   $this->load->view('welcome_message');
  }
  else
  {
   $this->load->view('formsuccess');
  }
 }
}
application\views\welcome_message.php
<?php echo validation_errors(); ?>

<?php echo form_open('welcome'); ?>

<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

<div><input type="submit" value="Submit" /></div>

</form>
Showing Errors Individually
<h5>Username</h5>
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<?php echo form_error('password'); ?>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<?php echo form_error('passconf'); ?>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<?php echo form_error('email'); ?>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

Insert – Edit – Delete Codeigniter


Insert – Edit – Delete Codeigniter 

Create Database

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `username` varchar(15) NOT NULL,
  `password` text NOT NULL,
  `fullname` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
)

Setup Controller

application\controllers\user.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{ 
     /**
     * The __construct function is called so that I don't have to load the model each and every time.
     * And any change while refactoring or something else would mean change in only one place.
     */
    function __construct() {
        parent::__construct();
        $this->load->model('Model_user');
  $this->load->library('form_validation');
        $this->load->helper('form');
    }
 
    function index(){
        $data['query'] = $this->Model_user->getAll();
        $this->load->view('view_user/input',$data);
    }
 function submit(){
        if ($this->input->post('submit')){
                         
            if ($this->input->post('id')){
                $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
                $this->form_validation->set_rules('password', 'Password', 'matches[passconf]');
                $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
                 
                if ($this->form_validation->run() == FALSE){
                    $data['id'] = $this->input->post('id');
                    $data['username'] = set_value('username');
                    $data['fullname'] = set_value('fullname');
                    $this->load->view('view_user/edit',$data);
                }else{
                    $this->Model_user->update();
            redirect('view_user/index');
        }  
            }else{
                $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
                $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
                $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
                $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
             
        if ($this->form_validation->run() == FALSE){
                        $data['query'] = $this->Model_user->getAll();
                        $this->load->view('view_user/input',$data);
                }else{
              $this->Model_user->save();
            redirect('user/index');
        }
      }
        }
    }
     
    function edit(){ 
    $id=$this->uri->segment(3);
    $data['result']=$this->Model_user->getUser($id);
     
    if (empty($id) or count($data['result'])==0 ){
        redirect('user/index');
    }else{   
        $result=$this->Model_user->getUser($id);
        $data['id'] = $result['id'];
        $data['username'] = $result['username'];
            $data['fullname'] = $result['fullname'];
        $this->load->view('view_user', $data);
    }   
  }
   
  function delete($id){
    $this->db->delete('user', array('id' => $id));
        redirect('user/index');
  }
}
Model application\models\Model_user.php
<?php
class Model_user extends CI_Model{
     
 function getAll(){
        $this->db->select('id,username,fullname');
                $this->db->from('users');
                $this->db->limit(10);
                $this->db->order_by('id','ASC');
                $query = $this->db->get();
 
                return $query->result();
    }
     
    function getUser($id){
    $this->db->where('id', $id);
    $query = $this->db->get('users');
     
    return $query->row_array();
    }
     
    function save(){
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $fullname = $this->input->post('fullname');
    $data = array(
      'username'=>$username,
      'password'=>md5($password),
      'fullname'=>$fullname
    );
    $this->db->insert('users',$data);
  }
   
  function update(){
    $id   = $this->input->post('id');
        $username = $this->input->post('username');
        $password = $this->input->post('password');
    $fullname = $this->input->post('fullname');
    if ($password==''){
        $data = array(
      'username'=>$username,
      'fullname'=>$fullname
    );
    }else{
        $data = array(
      'username'=>$username,
      'password'=>md5($password),
      'fullname'=>$fullname
    );
    }
     
    $this->db->where('id',$id);
    $this->db->update('users',$data);   
  }
}
View application\views\view_user\input.php
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Data User</title>
  </head>
  <body>
    <div id="form_input" title="Input / Edit Data">
      <table>
        <?php echo validation_errors(); ?>
        <?php echo form_open('user/submit'); ?>
        <tr >
            <td> <?php echo form_label('User Name : '); ?></td>
            <td> <?php echo form_input('username',set_value('username'),'id="username"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Password : ');?> </td>
            <td> <?php echo form_password('password','','id="password"'); ?></td>
        </tr>
         <tr>
            <td> <?php echo form_label('Repeat Password : ');?> </td>
            <td> <?php echo form_password('passconf','','id="passconf"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Full Name : ');?> </td>
            <td> <?php echo form_input('fullname', set_value('fullname'),'id="fullname"'); ?></td>
        </tr>
        <tr>
                <td><?php echo form_submit('submit','Save')?>
        </tr>
      </table>
      </div>
      <div id="show">
        <?php $this->load->view('view_user/show'); ?>
    </div>
    </div>
  </body>
</html>
application\views\view_user\show.php
<?php
    if (isset($query) && count($query) > 0){
    ?>
    <h1>Data User</h1>
    <table width="400" border="1">
    <tr >
     <th>No</th>
     <th>Username</th>
     <th>Fullname</th>
     <th>Edit</th>
     <th>Delete</th>
 </tr>
 <?php
 $i=0;
 foreach ($query as $row){
 $i++;
 echo "<tr class=\"record\">";
 echo    "<td>$i</td>";
 echo    "<td>$row->username</td>";
 echo    "<td>$row->fullname</td>";
 echo    "<td><a href=".base_url()."index.php/user/edit/$row->id>Edit</a></td>";
 echo    "<td><a href=".base_url()."index.php/user/delete/$row->id>Delete</a></td>";
 echo  "</tr>";
 }
 ?>
</table>
<?php
    }
?>

Simple Login with CodeIgniter in PHP

Simple Login with CodeIgniter in PHP 

 Create the database

CREATE TABLE `users` (
 `id` tinyint(4) NOT NULL AUTO_INCREMENT,
 `username` varchar(10) NOT NULL,
 `password` varchar(100) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

insert into users (username, password) values ('admin', MD5('password'));
 
Configure CodeIgniter 

application/config/database.php 
 
Default Controller
application/config/routes.php 
call landing controller login
$route['default_controller'] = "login";
 
Default Libraries 
application/config/autoload.php
handle user sessions, and also the URL helper for internal link generation
$autoload['libraries'] = array('database','session');
$autoload['helper'] = array('url'); 

Encryption Key
application/config/config.php
$config['encryption_key'] = 'REALLY_LONG_NUMBER';
 
The Code
 
User Model (application/models/user.php) 

<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('id, username, password');
   $this -> db -> from('users');
   $this -> db -> where('username', $username);
   $this -> db -> where('password', MD5($password));
   $this -> db -> limit(1);

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

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }
}
?>
Login Controller (application/controllers/login.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

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

 function index()
 {
   $this->load->helper(array('form'));
   $this->load->view('login_view');
 }

}

?>
Login View (application/views/login_view.php)
   <h1>Simple Login with CodeIgniter</h1>
   <?php echo validation_errors(); ?>
   <?php echo form_open('verifylogin'); ?>
     <label for="username">Username:</label>
     <input type="text" size="20" id="username" name="username"/>
     <br/>
     <label for="password">Password:</label>
     <input type="password" size="20" id="passowrd" name="password"/>
     <br/>
     <input type="submit" value="Login"/>
   </form>
VerifyLogin Controller (application/controllers/verifylogin.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

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

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }

 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');

   //query the database
   $result = $this->user->login($username, $password);

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>
Home Controller (application/controllers/home.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class Home extends CI_Controller {

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

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home_view', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('home', 'refresh');
 }

}

?>
Home Page View (application/views/home_view.php)
<html>
 <head>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body>
   <h1>Home</h1>
   <h2>Welcome <?php echo $username; ?>!</h2>
   <a href="home/logout">Logout</a>
 </body>
</html>

How to enable or disable an anchor using jQuery

How to enable or disable an anchor using jQuery To prevent an anchor from following the specified href
$(document).ready(function() {
    $('a.something').click(function(e) {
        e.preventDefault();
    });
});

Passing array of checkbox values to php through jQuery

Passing array of checkbox values to php through jQuery 
 
//index.hmtl
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
                function doit() {
                        var p=[];
                        $('input.cb').each( function() {
                                if($(this).attr('checked')) {
                                        p.push($(this).attr('rel'));
                                }
                        } );
                        $.ajax( {
                                url:'process.php',
                                type:'POST',
                                data: {list:p},
                                success: function(res) {
                                        alert(res);
                                }
                        });
                }
        </script>

        <input type="checkbox" class="cb" rel="1"></input>Test 1<br />
        <input type="checkbox" class="cb" rel="2"></input>Test 2<br />
        <input type="checkbox" class="cb" rel="3"></input>Test 3<br />
        <a href="javascript:void(0)" onclick="doit()">Click</a>
//process.php
<?php
print_r(@$_POST['list']);
?>

Tuesday, July 30, 2013

Delete Confirmation using Javascript

Delete Confirmation using Javascript 
 
<script>
function confirmDelete()
{
    return confirm("Are you sure you wish to delete this entry?");
}
</script>
<a href="?action=delete&id=3" onclick="return confirmDelete();"> Delete this entry</a>

PHP Tutorial: Classes and OOP

PHP Tutorial: Classes and OOP 

 
<?php
//PHP Tutorial: Classes and OOP
//The first thing you do is to define the class:
class cow
{
}
//Next, we'll create our first function - this is defined exactly the same as if you were not using classes:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
//create the new class object 'in' a variable
// Create new cow object
$daisy = new cow;
//then call the moo() function
echo $daisy->moo();

//If you put this code together then, you will get something like this:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
// Create new cow object
$daisy = new cow;
echo $daisy->moo();

//Ex. more functions
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

//call these functions and try out the new class
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced

//final version
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();

echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
?>

Saturday, July 27, 2013

Style a Select Box Using CSS

Style a Select Box Using CSS
 
<style>
.styled-select select {
   background: transparent;
   width: 268px;
   padding: 5px;
   font-size: 16px;
   line-height: 1;
   border: 0;
   border-radius: 0;
   height: 34px;
   -webkit-appearance: none;
   }
   .styled-select {
   width: 240px;
   height: 34px;
   overflow: hidden;
   background: url(down_arrow_select.jpg) no-repeat right #ddd;
  
   display:block;font-size:16px;outline:0 none;padding:.4em;text-shadow:0 1px 0 #fff;-moz-border-radius:.6em;-webkit-border-radius:.6em;border-radius:.6em;border:1px solid #aaa;color:#333;text-shadow:0 1px 0 #fff;
   }
</style>
<div class="styled-select">
   <select>
      <option>Male</option>
      <option>Female</option>
   </select>
</div>

Friday, July 26, 2013

PHP, jQuery and MySQL Search

PHP, jQuery and MySQL Search
//index.html
<style>
body{ font-family:Arial, Helvetica, sans-serif; }
*{ margin:0;padding:0; }
#container { margin: 0 auto; width: 600px; }
a { color:#DF3D82; text-decoration:none }
a:hover { color:#DF3D82; text-decoration:underline; }
ul.update { list-style:none;font-size:1.1em; margin-top:10px }
ul.update li{ height:30px; border-bottom:#dedede solid 1px; text-align:left;}
ul.update li:first-child{ border-top:#dedede solid 1px; height:30px; text-align:left; }
#flash { margin-top:20px; text-align:left; }
#searchresults { text-align:left; margin-top:20px; display:none; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#000; }
.word { font-weight:bold; color:#000000; }
#search_box { padding:4px; border:solid 1px #666666; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
.search_button { border:#000000 solid 1px; padding: 6px; color:#000; font-weight:bold; font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
.found { font-weight: bold; font-style: italic; color: #ff0000; }
h2 { margin-right: 70px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $(".search_button").click(function() {
        // getting the value that user typed
        var searchString    = $("#search_box").val();
        // forming the queryString
        var data            = 'search='+ searchString;
         
        // if searchString is not empty
        if(searchString) {
            // ajax call
            $.ajax({
                type: "POST",
                url: "do_search.php",
                data: data,
                beforeSend: function(html) { // this happens before actual call
                    $("#results").html('');
                    $("#searchresults").show();
                    $(".word").html(searchString);
               },
               success: function(html){ // this happens after we get results
                    $("#results").show();
                    $("#results").append(html);
              }
            });   
        }
        return false;
    });
});
</script>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
</form>
</div>     
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
//do_search.php
<?php
//if we got something through $_POST
if (isset($_POST['search'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $word = mysql_real_escape_string($_POST['search']);
    $word = htmlentities($word);
    // build your search query to the database
    $sql = "SELECT title, url FROM pages WHERE content LIKE '%" . $word . "%' ORDER BY title LIMIT 10";
    // get results
    $row = $db->select_list($sql);
    if(count($row)) {
        $end_result = '';
        foreach($row as $r) {
            $result         = $r['title'];
            // we will use this to bold the search word in result
            $bold           = '<span class="found">' . $word . '</span>';   
            $end_result     .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';           
        }
        echo $end_result;
    } else {
        echo '<li>No results found</li>';
    }
}
?>

Username availability check using PHP and jQuery

Username availability check using PHP and jQuery
 
<?php

/* CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(150) NOT NULL,
`email` varchar(100) NOT NULL',
`pass` varchar(100)  NOT NULL',
PRIMARY KEY (`id`)
) */
//Username availability check using PHP and jQuery
//if we got something through $_POST
if (isset($_POST['user'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $username = mysql_real_escape_string($_POST['user']);
    // build your query to the database
    $sql = "SELECT count(*) as num FROM users WHERE username = " . $username;
    // get results
    $row = $db->select_single($sql);
    if($row['num'] == 0) {
        echo 'Username <em>'.$username.'</em> is available!';
    } else {
        echo 'Username <em>'.$username.'</em> is already taken!';
    }
}
?>
<script>
$(function() {
$("#sub").click(function() {
    // getting the value that user typed
    var checkString    = $("#username_box").val();
    // forming the queryString
    var data            = 'user='+ checkString;
 
    // if checkString is not empty
    if(checkString) {
        // ajax call
        $.ajax({
            type: "POST",
            url: "do_check.php",
            data: data,
            beforeSend: function(html) { // this happen before actual call
                $("#results").html('');
            },
            success: function(html){ // this happen after we get result
                $("#results").show();
                $("#results").append(html);
            }
        });
}
return false;
});
});
</script>
<form action="do_check.php" method="post">
    <input id="username_box" class="search_box" name="username" type="text" />
    <input id="sub" type="submit" value="Check" />
</form>

Thursday, July 25, 2013

Using Sessions in WordPress Plugins

Using Sessions in WordPress Plugins 

In your theme/plugin

Add the next piece of code to your functions.php or plugin file to enable sessions:

/**
 * init_sessions()
 *
 * @uses session_id()
 * @uses session_start()
 */
function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

PHP Multiple Atachment Send

PHP Multiple Atachment Send 


E-mail with Attachment
 <?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

   // we'll begin by assigning the To address and message subject
   $to="somebody@example.com";
   $subject="E-mail with attachment";

   // get the sender's name and email address
   // we'll just plug them a variable to be used later
   $from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";

   // generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // now we'll build the message headers
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   // here, we'll start the message body.
   // this is the text that will be displayed
   // in the e-mail
   $message="This is an example";

   // next, we'll build the invisible portion of the message body
   // note that we insert two dashes in front of the MIME boundary 
   // when we use it
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){
      // store the file information to variables for easier access
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

      // if the upload succeded, the file will exist
      if (file_exists($tmp_name)){

         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
  
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
  
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
  
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }
  
         // now we'll insert a boundary to indicate we're starting the attachment
         // we have to specify the content type, file name, and disposition as
         // an attachment, then add the file content.
         // NOTE: we don't set another boundary to indicate that the end of the 
         // file has been reached here. we only want one boundary between each file
         // we'll add the final one after the loop finishes.
         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }
   // here's our closing mime boundary that indicates the last of the message
   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" 
   enctype="multipart/form-data" name="form1">
   <p>From name: <input type="text" name="fromname"></p>
   <p>From e-mail: <input type="text" name="fromemail"></p>
   <p>File: <input type="file" name="file1"></p>
   <p>File: <input type="file" name="file2"></p>
   <p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>

Sanitize Input Form

Sanitize Input Form

 
<?php
include('connect.php');
$conn = db_connect();
 
 function cleanInput($input) {
  $search = array(
   '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
   '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
   '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
   '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
 );
  $output = preg_replace($search, '', $input);
  return $output;
 }

?>
<?
if(isset($_POST["submit"]))
{
 $_username = cleanInput($_POST["_username"]);
 $_password = md5($_POST["_password"]);  
 $sql_insert = "INSERT INTO tbl_admin(_username, _password) VALUES ('$_username', '$_password')";
 $result = mysql_query($sql_insert);
 echo "records save"; 
 //echo "<script>
 //   window.location='index.php';
 //    </script>";
 //
}
?>
<div style="padding-left:50px; font-weight:bold; font-size:18px; margin-bottom:20px; color:#ffffff">
 ADD NEW Users
</div>
<form name="subjadd" action="" method="post">
 <table width="96%" border="0" cellspacing="3" cellpadding="4">
  <tr>
   <th>User name:</th>
   <td><input name="_username" type="text" size="40"></td>
  </tr>
  <tr>
   <th>Password</th>
   <td><input name="_password" type="text" size="40"></td>
  </tr>
  <tr>
   <th></th>
   <td>
    <input type="submit" name="submit" value="Add New!">
</td>
  </tr>
 </table>
</form>

Public, Private and Protected - PHP OOP

Public, Private and Protected - PHP OOP 

Example 
 
<?php
//Public Visibility in PHP Classes
//Public methods or variables can be accessible from anywhere. It can be accessible from using object(outside the class), or inside the class, or in child class.
class test
{
public $abc;
public $xyz;
public function xyz()
{
}
}

$objA = new test();
echo $objA->abc;//accessible from outside
$objA->xyz();//public method of the class test
?>

<?php
//Private Visibility in PHP Classes
//only be accessible withing the class. Private visibility in php classes is used when you do not want your property or function to be exposed outside the class.
Class test
{
public $abc;
private $xyz;
public function pubDo($a)
{
echo $a;
}
private function privDo($b)
{
echo $b;
}
public function pubPrivDo()
{
$this->xyz = 1;
$this->privDo(1);
}
}
$objT = new test();
$objT->abc = 3;//Works fine
$objT->xyz = 1;//Throw fatal error of visibility
$objT->pubDo("test");//Print "test"
$objT->privDo(1);//Fatal error of visibility
$objT->pubPrivDo();//Within this method private function privDo and variable xyz is called using $this variable.
?>


<?php
//Protected Visibility in PHP Classes
//useful in case of inheritance and interface. Protected method or variable can be accessible either within class or child class.
class parent
{
protected $pr;
public $a
protected function testParent()
{
echo this is test;
}
}
class child extends parent
{
public function testChild()
{
$this->testParent(); //will work because it
}
}
$objParent = new parent();
$objParent->testParent();//Throw error
$objChild = new Child();
$objChild->setChild();//work because test child will call test parent.
?>

Saturday, July 13, 2013

Clearing File Input Values

Clearing File Input Values


 
<script type="text/javascript">
        function clearFileInput( id )
        {
            var elem = document.getElementById( id );
            elem.parentNode.innerHTML = elem.parentNode.innerHTML;
        }
    </script>

    <form method="post" enctype="multipart/form-data">
        <input type="file" name="myFile" id="fileInput1" />
        <input type="submit" name="s" value="Upload" />
    </form>
    <a href="javascript:clearFileInput( 'fileInput1' );">Clear File Input Value</a>

Get URL Parameters Using Javascript

Get URL Parameters Using Javascript

 
function getparamurl( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var get_param = getparamurl('getid');
alert(get_param);
http://tutorial101.blogspot.com/index.html?getid=123

Related Post