Saturday, 31 December 2016

PHP for loop 1st, 2nd, 3rd, 4th, 5th, 6th – PHP Add Ordinal Number Suffix


<?php

  function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100),array(11,12,13))){
      switch ($num % 10) {
        // Handle 1st, 2nd, 3rd
        case 1:  return $num.'st';
        case 2:  return $num.'nd';
        case 3:  return $num.'rd';
      }
    }
    return $num.'th';
  }

?>
for ($i = 1; $i <= 10000; $i++){
  echo addOrdinalNumberSuffix($i) . "\t";
  if ($i % 10 == 0) {
    echo "\n";
  }
}
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 
11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 
21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 
31st 32nd 33rd 34th 35th 36th 37th 38th 39th 40th 
41st 42nd 43rd 44th 45th 46th 47th 48th 49th 50th 
51st 52nd 53rd 54th 55th 56th 57th 58th 59th 60th 
61st 62nd 63rd 64th 65th 66th 67th 68th 69th 70th 
71st 72nd 73rd 74th 75th 76th 77th 78th 79th 80th 
81st 82nd 83rd 84th 85th 86th 87th 88th 89th 90th 
91st 92nd 93rd 94th 95th 96th 97th 98th 99th 100th 
101st 102nd 103rd 104th 105th 106th 107th 108th 109th 110th

Bootstrap Dynamic Tabs







CODE

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 3 Dynamic Tabs</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#myTab a").click(function(e) {
                e.preventDefault();
                $(this).tab('show');
            });
        });
    </script>
    <style type="text/css">
        .bs-example {
            margin: 20px;
        }
    </style>
</head>

<body>
    <div class="bs-example">
        <ul class="nav nav-tabs" id="myTab">
            <li class="active"><a href="#sectionA">Section A</a></li>
            <li><a href="#sectionB">Section B</a></li>
            <li class="dropdown">
                <a data-toggle="dropdown" class="dropdown-toggle" href="#">Dropdown <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="#dropdown1">Dropdown1</a></li>
                    <li><a href="#dropdown2">Dropdown2</a></li>
                </ul>
            </li>
        </ul>
        <div class="tab-content">
            <div id="sectionA" class="tab-pane fade in active">
                <h3>Section A</h3>
                <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
            </div>
            <div id="sectionB" class="tab-pane fade">
                <h3>Section B</h3>
                <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
            </div>
            <div id="dropdown1" class="tab-pane fade">
                <h3>Dropdown 1</h3>
                <p>WInteger convallis, nulla in sollicitudin placerat, ligula enim auctor lectus, in mollis diam dolor at lorem. Sed bibendum nibh sit amet dictum feugiat. Vivamus arcu sem, cursus a feugiat ut, iaculis at erat. Donec vehicula at ligula vitae venenatis. Sed nunc nulla, vehicula non porttitor in, pharetra et dolor. Fusce nec velit velit. Pellentesque consectetur eros.</p>
            </div>
            <div id="dropdown2" class="tab-pane fade">
                <h3>Dropdown 2</h3>
                <p>Donec vel placerat quam, ut euismod risus. Sed a mi suscipit, elementum sem a, hendrerit velit. Donec at erat magna. Sed dignissim orci nec eleifend egestas. Donec eget mi consequat massa vestibulum laoreet. Mauris et ultrices nulla, malesuada volutpat ante. Fusce ut orci lorem. Donec molestie libero in tempus imperdiet. Cum sociis natoque penatibus et magnis.</p>
            </div>
        </div>
    </div>
</body>
</html>


Bootstrap Dynamic Tabs 

Thursday, 29 December 2016

yii2 LIKE Condition in query

$model = User::find()
->where(['LIKE', 'username', 'admin'])
->all();
//OR

$model = User::find()->where('username LIKE :query')->addParams([':query'=>'%admin%'])
->all();


$model = User::find()->where(['NOT LIKE', 'username', 'admin'])->all();


yii2 LIKE Condition  in query

Monday, 26 December 2016

Jquery character and Message count textarea




JS

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#messageValue").keyup(function(){
//$("#count").text($(this).val().length);
var wordCount = $(this).val().length;
var messagePart = document.getElementById('message_part');
$("#characterCount").text(wordCount);
//alert(wordCount);
if (wordCount > 159) {
var z = wordCount / 160;
z = Math.floor(z);
z = z + 1; 
} else {
var z = 1;
}
messagePart.innerHTML = z;
});
});
</script>


HTML

<textarea name="message" id="messageValue" rows="10" placeholder="Message" required></textarea>
<div><span id="characterCount" style="color:#F00;">0</span> Characters in text Box. 
Send this Message in <span id="message_part" style="color:#F00;">1</span> Part                          
Jquery character and Message count textarea



javascript Jquery character count textarea



HTML

<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>

JS

$(document).ready(function() {
    var text_max = 99;
    $('#textarea_feedback').html(text_max + ' characters remaining');

    $('#textarea').keyup(function() {
        var text_length = $('#textarea').val().length;
        var text_remaining = text_max - text_length;

        $('#textarea_feedback').html(text_remaining + ' characters remaining');
    });
});

javascript character count textarea

Thursday, 22 December 2016

Multiple File Upload with PHP



HTML

<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Multiple File Ppload with PHP</title>
</head>

<body>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
        <input type="submit" value="Upload!" /> </form>
</body>

</html>

PHP CODE

$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {     
   if ($_FILES['files']['error'][$f] == 4) {
       continue; // Skip file if any error found
   }       
   if ($_FILES['files']['error'][$f] == 0) {           
       if ($_FILES['files']['size'][$f] > $max_file_size) {
           $message[] = "$name is too large!.";
           continue; // Skip large files
       }
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
       else{ // No error found! Move uploaded files 
           if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
           $count++; // Number of successfully uploaded file
       }
   }
}
}


Multiple File Upload with PHP

Upload Multiple Files and Images in CodeIgniter

CREATE TABLE

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL COMMENT 'Upload Date',
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Unblock, 0=Block',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CONTROLLER

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Upload_Files extends CI_Controller{
    function  __construct() {
        parent::__construct();
        $this->load->model('file');
    }
    
    function index(){
        $data = array();
        if($this->input->post('fileSubmit') && !empty($_FILES['userFiles']['name'])){
            $filesCount count($_FILES['userFiles']['name']);
            for($i 0$i $filesCount$i++){
                $_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
                $_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
                $_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
                $_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
                $_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];

                $uploadPath 'uploads/files/';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = 'gif|jpg|png';
                
                $this->load->library('upload'$config);
                $this->upload->initialize($config);
                if($this->upload->do_upload('userFile')){
                    $fileData $this->upload->data();
                    $uploadData[$i]['file_name'] = $fileData['file_name'];
                    $uploadData[$i]['created'] = date("Y-m-d H:i:s");
                    $uploadData[$i]['modified'] = date("Y-m-d H:i:s");
                }
            }
            
            if(!empty($uploadData)){
                //Insert file information into the database
                $insert $this->file->insert($uploadData);
                $statusMsg $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
                $this->session->set_flashdata('statusMsg',$statusMsg);
            }
        }
        //Get files data from database
        $data['files'] = $this->file->getRows();
        //Pass the files data to view
        $this->load->view('upload_files/index'$data);
    }

}
MODEL

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Model{

    public function getRows($id ''){
        $this->db->select('id,file_name,created');
        $this->db->from('files');
        if($id){
            $this->db->where('id',$id);
            $query $this->db->get();
            $result $query->row_array();
        }else{
            $this->db->order_by('created','desc');
            $query $this->db->get();
            $result $query->result_array();
        }
        return !empty($result)?$result:false;
    }
    
    public function insert($data = array()){
        $insert $this->db->insert_batch('files',$data);
        return $insert?true:false;
    }
    
}

VIEW

<div class="container">
    <div class="row">
        <p><?php echo $this->session->flashdata('statusMsg'); ?></p>
        <form enctype="multipart/form-data" action="" method="post">
            <div class="form-group">
                <label>Choose Files</label>
                <input type="file" class="form-control" name="userFiles[]" multiple/>
            </div>
            <div class="form-group">
                <input class="form-control" type="submit" name="fileSubmit" value="UPLOAD"/>
            </div>
        </form>
    </div>
    <div class="row">
        <ul class="gallery">
            <?php if(!empty($files)): foreach($files as $file): ?>
            <li class="item">
                <img src="<?php echo base_url('uploads/files/'.$file['file_name']); ?>" alt="" >
                <p>Uploaded On <?php echo date("j M Y",strtotime($file['created'])); ?></p>
            </li>
            <?php endforeach; else: ?>
            <p>Image(s) not found.....</p>
            <?php endif; ?>
        </ul>
    </div>
</div>

CONFIG

$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url');

Wednesday, 21 December 2016

PHP Image get file size MB , KB , GB, Byte conversion

<?php

    function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' kB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return $bytes;
}
?>

How to alert ajax response

$.ajax({
    url:"myscript.php",
    dataType: "json",
    success:function(data){
       var obj = jQuery.parseJSON(data);
       alert(obj.filename);
    }
});
$('#alertMessage').html(data.msg);