Monday, November 29, 2010

PHP Pagination

This is a guide how to create a pagination in PHP like digg.com pagination style  


Overview
This is a script to make pagination in PHP like digg.com or flickr.com.
This script was written by a guy from Stranger Studios. In this page I've edit the script a little bit to make it working and easy to edit. You can grab the original script at Digg-Style Pagination. My tutorial is just a guide how to implemente in your PHP script.
This is what you'll get after finished this code
PHP Pagination Script





The Code
Grab the code and paste in your text editor. 
You have to customize 7 spots in this code (see images below).
1. Code to connect to your DB - place or include your code to connect to database.
2. $tbl_name - your table name.
3. $adjacents - how many adjacent pages should be shown on each side.
4. $targetpage - is the name of file ex. I saved this file as pagination.php, my $targetpage should be "pagination.php".
5. $limit - how many items to show per page.
6. "SELECT column_name - change to your own column.
7. Replace your own while..loop here - place your code to echo results here.
After all, save and test your script

Apply CSS Style to your code
Save this code to style.css and link to your pagination page.
To get more CSS style click here
PHP pagination
<?php
    /*
        Place code to connect to your DB here.
    */
    include('config.php');    // include your code to connect to DB.

    $tbl_name="";        //your table name
    // How many adjacent pages should be shown on each side?
    $adjacents = 3;
  
    /*
       First get total number of rows in data table.
       If you have a WHERE clause in your query, make sure you mirror it here.
    */
    $query = "SELECT COUNT(*) as num FROM $tbl_name";
    $total_pages = mysql_fetch_array(mysql_query($query));
    $total_pages = $total_pages[num];
  
    /* Setup vars for query. */
    $targetpage = "filename.php";     //your file name  (the name of this file)
    $limit = 2;                                 //how many items to show per page
    $page = $_GET['page'];
    if($page)
        $start = ($page - 1) * $limit;             //first item to display on this page
    else
        $start = 0;                                //if no page var is given, set start to 0
  
    /* Get data. */
    $sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
    $result = mysql_query($sql);
  
    /* Setup page vars for display. */
    if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
    $prev = $page - 1;                            //previous page is page - 1
    $next = $page + 1;                            //next page is page + 1
    $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
    $lpm1 = $lastpage - 1;                        //last page minus 1
  
    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case we want to draw it more than once.
    */
    $pagination = "";
    if($lastpage > 1)
    {  
        $pagination .= "<div class=\"pagination\">";
        //previous button
        if ($page > 1)
            $pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>";
        else
            $pagination.= "<span class=\"disabled\">« previous</span>";  
      
        //pages  
        if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
        {  
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                  
            }
        }
        elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
        {
            //close to beginning; only hide later pages
            if($page < 1 + ($adjacents * 2))      
            {
                for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<span class=\"current\">$counter</span>";
                    else
                        $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                  
                }
                $pagination.= "...";
                $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";      
            }
            //in middle; hide some front and some back
            elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
                $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                $pagination.= "...";
                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<span class=\"current\">$counter</span>";
                    else
                        $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                  
                }
                $pagination.= "...";
                $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";      
            }
            //close to end; only hide early pages
            else
            {
                $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                $pagination.= "...";
                for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<span class=\"current\">$counter</span>";
                    else
                        $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                  
                }
            }
        }
      
        //next button
        if ($page < $counter - 1)
            $pagination.= "<a href=\"$targetpage?page=$next\">next »</a>";
        else
            $pagination.= "<span class=\"disabled\">next »</span>";
        $pagination.= "</div>\n";      
    }
?>

    <?php
        while($row = mysql_fetch_array($result))
        {
  
        // Your while loop here
  
        }
    ?>

<?=$pagination?>

   




These are where you have to customize the script


PHP paginationPHP paginationPHP pagination

Friday, November 26, 2010

Special Thanks To Bilu

Special Thanks to bilu, the man behind the beautiful logo...and banner

How to make a selection based on the beginning value

An SQL command that selects the field’s values that start with a specific string.

SELECT * FROM `your_table_here` WHERE field_table REGEXP '^string_here';

The symbol ^ is telling MySQL to look at the beginning of the value.

How to make a selection based on the ending value

An SQL command that selects the field’s values that end with a specific string.

SELECT * FROM `your_table_here` WHERE field_table REGEXP 'string_here$'; 

The symbol $ is telling MySQL to look at the ending of the value.

Get maximum ID from a table

To get the maximum id from a table you can use the MAX() function.
Here’s an example:

SELECT MAX(id_field_here) as max_id FROM `table`;

Calculating value from percent

This short tutorial is aimed to help you how to calculate the percent value from a total. Let’s suppose you have a e-commerce site and you offer discounts to the customers. You need to show them how much is the discount value worthing

Here’s a sample from an order total:
Notebook’s price: $1,300
Our special discount: 30% (-$390)
Final price: $910

 <?php
$percent = '30'; // without %
$total = '1300'; // initial value

/* Calculate $percent% from $total */
$discount_value = ($total / 100) * $percent;

$final_price = $total - $discount_value;

// Format numbers with number_format()

$total = number_format($total);
$discount_value = number_format($discount_value);
$final_price = number_format($final_price);

echo "Notebook's price: $".$total."<br />Our special discount: <strong>".
$percent."%</strong> (-$".$discount_value.")<br />Final price: $".$final_price;
?>

How to replace multiple spaces from a string in PHP

This snippet is useful when you need to replace multiple spaces from a string. Tabs, New Lines and Carriages are also replaced.

<?php
function replace_multiple_spaces($string)
{
    // tabs, new lines and carriages are also replaced
$string = ereg_replace("[ \t\n\r]+", " ", $string);

return $string;
}

$string = "This
   is
a   dummy
text. ";

$new_string = replace_multiple_spaces($string);

// Outputs: This is a dummy text
echo $new_string;
?>

How to calculate age in PHP

Here’s a simple php function that calculates the age of someone, in years.

<?php

function determine_age($birth_date)
{
$birth_date_time = strtotime($birth_date);
$to_date = date('m/d/Y', $birth_date_time);

list($birth_month, $birth_day, $birth_year) = explode('/', $to_date);

$now = time();

$current_year = date("Y");

$this_year_birth_date = $birth_month.'/'.$birth_day.'/'.$current_year;
$this_year_birth_date_timestamp = strtotime($this_year_birth_date);

$years_old = $current_year - $birth_year;

if($now < $this_year_birth_date_timestamp)
{
/* his/her birthday hasn't yet arrived this year */
$years_old = $years_old - 1;
}

return $years_old;
}

// You can write about any English textual datetime description

$birth_date = '1 May 1980';

$age = determine_age($birth_date);

echo $age;
?>

Get filename extension

Get filename extension...
<?php
... some code here ...
// Filename
$filename = 'public_html/root/internet.gif';
// Extension
$ext = strrchr($filename, ".");
echo $ext; // will return ".gif"
?>

Update table field by replacing a string value with a new one

Let’s suppose you have a mysql database and you need to update only a part of a field’s value, not all.

UPDATE `table` SET `field` = REPLACE(`field`, "old_string", "new_string");

PHP: How to remove empty values from an array

This function removes empty values from an array. This is useful if you’re working with dynamical arrays (for instance data harvested from a web site).

<?php
function remove_array_empty_values($array, $remove_null_number = true)
{
    $new_array = array();

    $null_exceptions = array();

    foreach ($array as $key => $value)
    {
        $value = trim($value);

        if($remove_null_number)
        {
            $null_exceptions[] = '0';
        }

        if(!in_array($value, $null_exceptions) && $value != "")
        {
            $new_array[] = $value;
        }
    }
    return $new_array;
}
?>


Example of usage:
 $array = array("white", "yellow", 0, "green", " ", "navy");

$remove_null_number = true;
$new_array = remove_array_empty_values($array, $remove_null_number);

echo '<pre>'; print_r($new_array); echo '</pre>';

The new array will look like this:
 
Array
(
    [0] => white
    [1] => yellow
    [2] => green
    [3] => navy
)

Create PDF with PHP

The PDF extension of PHP (PDFlib) provides the required functionality for generating PDF files.
The following sample code demonstrates how a PDF file can be created and filled with
information retrieved from database:
 
<?php
// select data from database for the PDF
mysql_select_db($database_cnnTest, $cnnTest);
$query_rsReportData = "SELECT * FROM categories";
$rsReportData = mysql_query($query_rsReportData, $cnnTest) or die(mysql_error());
$row_rsReportData = mysql_fetch_assoc($rsReportData);
$totalRows_rsReportData = mysql_num_rows($rsReportData);
?>
<?php
// create handle for new PDF document
$pdf = pdf_new();

// open a file
pdf_open_file($pdf, "");

// Set Info
pdf_set_info($pdf, "Author", "Georgi Kralev");
pdf_set_info($pdf, "Title", "Report");
pdf_set_info($pdf, "Creator", "Georgi Kralev");
pdf_set_info($pdf, "Subject", "Report");

// start a new page (A4)
pdf_begin_page($pdf, 595, 842);

// path of your TTF font directory
$fontdir = "C:\WINDOWS\Fonts";

// Open .TTFs (true type fonts)

pdf_set_parameter($pdf, "FontOutline", "ArialItalic=$fontdir\ariali.ttf");
pdf_set_parameter($pdf, "FontOutline", "ArialBold=$fontdir\ARIALBD.TTF");
pdf_set_parameter($pdf, "FontOutline", "Arial=$fontdir\ARIAL.TTF");

// ------ Start output of the PDF Content ------//
// set the font - Arial Bold 15

$font = pdf_findfont($pdf, "ArialBold", "host",0); pdf_setfont($pdf, $font, 15); 
// output document title
pdf_show_xy($pdf, "Categories Report", 50, 788);
// draw a line
pdf_moveto($pdf, 20, 780);
pdf_lineto($pdf, 575, 780);
pdf_stroke($pdf);

// set the font - Arial Italic 12
$font = pdf_findfont($pdf, "ArialItalic", "host",0); pdf_setfont($pdf, $font, 12);
$y = 750;
// output data header
pdf_show_xy($pdf, "Category:", 50, $y);
$y -= 5;

// set the font - Arial 10
$font = pdf_findfont($pdf, "Arial", "host",0); pdf_setfont($pdf, $font, 10);

// output the data from Database
do
{
      $y -= 15;
        pdf_show_xy($pdf, $row_rsReportData['name'], 50, $y);
}
while
($row_rsReportData = mysql_fetch_assoc($rsReportData));

// ------ End output of the PDF Content ------//

// end page
pdf_end_page($pdf);

// close and save file
pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=report.pdf");
echo $buf;

pdf_delete($pdf);
?>
<?php
mysql_free_result($rsReportData);
?>
 

PHP - Getting notice Undefined index

 The PHP notice errors are frustrating and you are 
tired of seeing them when you are working on your scripts.
 They are showed at the beggining of your pages and may 
reveal confidential information to the visitor like the path 
to the file or the php file name in some cases 

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting(E_ALL);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Function ereg() is deprecated

If you upgraded to PHP 5.3, chances are high you’re going to run into a few warnings or deprecated function messages.
An example is the ereg family of functions, which are gone for good, as they were slower and felt less familiar than the alternative Perl-compatible preg family.

Replace
ereg('\.([^\.]*$)', $this->file_src_name, $extension);
 
with
preg_match('/\.([^\.]*$)/', $this->file_src_name, $extension);
 
Notice that I wrapped the pattern (\.([^\.]*$)) around / /
which are RegExp delimiters. If you find yourself escaping / 
too much (for an URL for example), 
you might want to use the # delimiter instead. 

PHP ,strip html tags using 'strip_tags'

The strip_tags() function strips a string from HTML, XML, and PHP tags.
Example:

<?php
echo strip_tags("Hello <b>world!</b>");
?> 

Output:
Hello world!

Saturday, November 13, 2010

IP to LongIP

 Converting standart IP format to long IP format.

function mbmIp2Long($ip) {
    $ex = explode(".", $ip);
    if (count($ex)!=4) return -1;
    list($a, $b, $c, $d) = $ex;
    $a = $a*16777216;
    $b = $b*65536;
    $c = $c*256;
    return $a+$b+$c+$d;
}

  1. echo mbmIp2Long(getenv("REMOTE_ADDR")); 

Disable all links via jQuery

Grabbing element with jQuery is very easy. In this example i’ll disable all links using jQuery.

<script>
$(function(){
    //grab all a tags
    $('a').each(function(){
        //click on a link....
        $(this).click(function(){
            alert($(this).attr('href')+' is not available');
            //disable link
            return false;
        });
    });
});
</script>

Image Slider

<div id="myIMG" style="display: none;"></div>

<script>
$(function(){

    total_img = 3;

    img = Array();
    img[0] = 'http://ip.skyzone.mn/mb_images/header_computer.jpg';
        img[1] = 'http://ip.skyzone.mn/mb_images/header_mobile.jpg';
        img[2] = 'http://ip.skyzone.mn/mb_images/header_voip.jpg';

    lnk = Array();
    lnk[0] = 'link1';
        lnk[1] = 'link2';
        lnk[2] = 'link3';

    showIMG(0,'#myIMG');

});

    function showIMG(idx, target_div){
        if(idx == total_img){
            idx = 0;
        }
        $(target_div).css('display','none');
        $(target_div).html('<a href="'+lnk[idx]+'" target="_blank"><img src="'+img[idx]+'" border="0" /></a>');
        $(target_div).fadeIn(3000);
        idx++;
        //alert(idx);
        setTimeout("showIMG("+idx+",'"+target_div+"');",5000);
    }
</script>

Multiple Checkbox Validation

How to validate the checkbox using Jquery?

In the HTML form have multiple chekcbox in same using html array element.
That time we will use three types of checkbox validation for checked or not.
Checkbox validation has three types.
  • Checkbox validation using Id
  • Checkbox validation using name
  • Checkbox validation using div tag
Example

Checkbox validation using Id

<form>
    <div id="checkboxId">
    <input type="checkbox" name="chkBox[]" id="chkBox[]">
    <input type="checkbox" name="chkBox[]" id="chkBox[]">
    <input type="checkbox" name="chkBox[]" id="chkBox[]">
    </div>
    <input type="button" name="Btnaction" value="submit" 
onclick="return validateId();">
</form>
</div>
<script language="javascript" src="jquery.js" type="text/javascript">
</script>
<script language="javascript">
function validateId()
{
 var selector_checked = $("input[@id=chkBox]:checked").length;
    alert(selector_checked);
    if (selector_checked == 0)
    {
        return false;
    }
    else if (selector_checked == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}
</script>

Checkbox validation using Name

function validateName()
{
    var selector_checked = $("input[@name=chkBox]:checked").length;
    alert(selector_checked);
    if (selector_checked == 0)
    {
        return false;
    }
    else if (selector_checked == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

Checkbox validation using Div tag

function validateDiv()
{
    if($("#checkboxId input[type='checkbox']:checked").length > 0)
    {
     return true;
    }
}

What is Jquery?

What is Jquery?
Jquery is one of the javascript library file. We can easy to integrate the website. Jquery is client side scripting language.
How to install the Jquery in web page?
Step 1:
First download the Jquery library file.
See the current release
Download Latest Jquery Version
Step 2:
Put the downloaded file in where you need in your website

For Example :

<html>
    <head>
         <title>Example page for Jquery</title>
         <script language="javascript" type="text/javascript" src="jquery-1.3.2.min.js"></script>
    </head>
</html>

How to select all and unselect all checkbox using Jquery

<form>
    <div id="checkboxId">\n
    <input type="checkbox" name="chkBox[]" id="chkBox[]">
    <input type="checkbox" name="chkBox[]" id="chkBox[]">
    <input type="checkbox" name="chkBox[]" id="chkBox[]">
    </div>\n
    <input type="checkbox" name="selectAll" id="selectAll" 
onclick="selectAllCheckbox('checkboxId', this);">
</form>
</div>
<script language="javascript" src="jquery.js" 
type="text/javascript">
</script>
<script language="javascript">
function selectAllCheckbox(divname, obj)
{  

 if (obj.checked)
 {\n
  $"#" + divname + " input[type='checkbox']").attr('checked', true);
 }
else
 {
 $("#" + divname + " input[type='checkbox']").attr('checked', false);
}
}
</script>

Thursday, November 4, 2010

Retrieving an RSS Feed in PHP

RSS Feeds are widely used throughout the internet today and on all kinds of websites. From websites like Digg to most blogs. If you want to display an RSS feed on your website its probably easier than you think.
For this example I'm going to show you how to display the RSS feed for The Tutorial Blog using PHP.

The Code

The first two lines of code that we write are going to be what retrieve the RSS feed.

$file = file_get_contents("http://www.thetutorialblog.com/feed/");
$xml = new SimpleXMLElement($file);

Now the next thing we do is use the foreach function so for each item found do something with it
foreach($xml->channel->item as $feed){
echo $feed->title.'<br>';
}

What are code will do is simply echo the titles of all the items found within the feeds. If you also want to include a link to the feed you can do this by printing to screen $feed->link. All the code together should look something like this.

<?php $file = file_get_contents("http://www.thetutorialblog.com/feed/");
$xml = new SimpleXMLElement($file);
foreach($xml->channel->item as $feed){
echo $feed->title.'<br>';
}
?>
Thanks for taking the time to read this tutorial. I hope you have learned something.

PHP CONTACT FORM

Every website needs a way of contacting the people behind it and putting an email on a page is not such a good idea; because bots can easily pick up this email address and send spam to it. This is where a contact form comes in very useful because people can send you messages but do not get your email address.
For a contact form the first thing that we need to do is to create a form using HTML so that they can input their information and message that they are going to send.
<form action="send_message.php" method="POST">
 Name: <input type="text" name="name"> <br />
 Email: <input type="text" name="email"> <br />
 Message: <textarea name="message"></textarea> <br />
 <input type="submit" name="send_message" value="Send!">
</form>
When the press send it will then go to a page called send_message.php. This page will grab the information that they input and send it to an email address using the mail() function in PHP.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
 
$to = 'your_address@your_email.com';
$subject = "New message from $name";
 
mail($to, $subject, $message, "From: $email");
echo "Message sent";
?>
We need to check that the sender of the message is human so we will add a simple math question to the bottom of our form.
<?php
 
 $num_one = rand() % 10;
 $num_two = rand() & 10;
 $final_num = $num_one + $num_two;
 $_SESSION['answer'] = $final_num;
 echo $num_one . ' + ' . $num_two . ' = ';
 ?>
    <input type="text" name="answer" /> <br />
Don't forget to add
<?php
session_start();
?>
To the top of the page or we will get errors.
Now we check to see if they have entered information into every field and that the answer to the math question is correct, if it is the message will be sent otherwise an error will be returned.
All the code for the form is:
<?php
session_start();
?>
<form action="send_message.php" method="POST">
 Name: <input type="text" name="name"> <br />
 Email: <input type="text" name="email"> <br />
 Message: <textarea name="message"></textarea> <br />
    <?php
 
 $num_one = rand() % 10;
 $num_two = rand() & 10;
 $final_num = $num_one + $num_two;
 $_SESSION['answer'] = $final_num;
 echo $num_one . ' + ' . $num_two . ' = ';
 ?>
    <input type="text" name="answer" /> <br />
 <input type="submit" name="send_message" value="Send!">
</form>
All the code for error checking and sending the message is:
<?php
session_start();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$user_answer = $_POST['answer'];
$real_answer = $_SESSION['answer'];
 
$to = 'your_address@your_email.com';
$subject = "New message from $name";
 
if(empty($name) OR empty($email) OR empty($message)) {
 echo "Fill in all fields.";
} elseif($user_answer != $real_answer) {
 echo "Math question was incorrect, please try again";
} else {
 mail($to, $subject, $message, "From: $email");
 echo "Message sent";
}
?>

5 PHP Frameworks you may not know about

Segull

Seagull 5 PHP Frameworks you may not know about
Supports:

* PHP4
* PHP5
* Multiple Database's
* ORM
* DB Objects
* Templates
* Caching
* Validation
* Ajax
* Auth Module
* Modules

PHP on TRAX

phpontrax 5 PHP Frameworks you may not know about
Supports:

* PHP5
* Multiple Database's
* ORM
* DB Objects
* Validation
* Ajax
* Modules

Yii

Yii 5 PHP Frameworks you may not know about
Supports:

* PHP5
* Multiple Database's
* ORM
* DB Objects
* Templates
* Caching
* Validation
* Ajax
* Auth Module
* Modules

Akelos

Akelos 5 PHP Frameworks you may not know about
Supports:

* PHP4
* PHP5
* Multiple Database's
* ORM
* DB Objects
* Templates
* Caching
* Validation
* Ajax
* Auth Module
* Modules

Prado

PRADO 5 PHP Frameworks you may not know about
Supports:

* PHP5
* Multiple Database's
* ORM
* DB Objects
* Templates
* Caching
* Validation
* Ajax
* Auth Module
* Modules

Wednesday, November 3, 2010

Javascript to show how many characters are remaining to enter in textbox or textarea

<label for="mytextbox">Your Name : </label>
<input type="input" id="mytextbox" maxlength="20" onkeyup="javascript:countCharacters('mycounter',20,'mytextbox')">

<span id="mycounter">20</span>

And "onKeyUp" event of the textbox we are calling a javascript function "countCharacters()".

we will be writing a standard function which accepts only some parameters and rest of the processing will be done in the function.

To this function we have to pass 3 parameters
1) id of the span - where counter will be shown when user types something
2) max_chars - length of the textarea which we specified in maxlength="20"
3) myelement - the id of the textbox where user types text

The function is as below


//http://programming-in-php.blogspot.com/
function countCharacters(id,max_chars,myelement)
{
counter = document.getElementById(id);
field = document.getElementById(myelement).value;
field_length = field.length;
 if (field_length <= max_chars)  {   
// Here we Calculate remaining characters   
remaining_characters = max_chars-field_length; 
  // Now Update the counter on the page
   counter.innerHTML = remaining_characters;
  }
 } 

onclick select the text of a textarea

<textarea rows="8" cols="40" onclick="this.focus();this.select()">
   some text here
   some text here
</textarea>

Simple pleasures with jQuery

omethings it’s the simple things in life that make you really happy.  For me yesterday, that was thanks to jQuery.  Have you ever wanted to have a check box that, when the user checks it it also checks a lot of other checkboxes?  Yeah, of course you have!  I wanted to do that yesterday.  Now, it’s not the first time I’ve had to do that kind of functionality, but it always came with a bunch of javascript that seemed over the top for what was wanted.  With jQuery it just took a line or two of code!
$(document).ready(function() {
        $('#selectall').click(function() {
         $(":checkbox", $('#checkboxlist')).attr('checked', $(this).is(':checked'));
        });
    });
And with that, on and off go the other checkboxes.
Marvelous!

Tuesday, November 2, 2010

Show Hide Div tag in Javascript and JQuery

I have been playing with JQuery for the past few days. After getting tired of writing lines and lines of code in javascript, Jquery does the same functionality with a couple of lines.
Let’s see a small comparison between a javascript code and JQuery.
Task: To show and hide a div tag with contents in it.
Most web developers come across this situation to show and hide the div contents – Let’s simply say it as toggle div tags

Now, comes the javascript code to toggle div tag
HTML

<a onclick="toggleDivTag(‘testfooter’);" href="#">Click here </a> <div id="testfooter">This is foo</div>
Javascript

<script type="text/javascript">// <![CDATA[
     function toggleDivTag(id) {        var divID = document.getElementById(id);        if(divID.style.display == 'block')           divID.style.display = 'none';        else           divID.style.display = 'block';     }
// ]]></script>
Explanation:

When you click on the link, the javascript function toggleDivTag was called along with a parameter, here ‘testfooter’. This parameter is the id of the div tag,. This div element should be closed and opened, when clicked.
In the javascript code, we are assigning the id of the particular div tag to a variable divID. Now, we are checking whether the div tag is visible or closed. If the div is shown, then we are applying the style as “none” to hide the div tag and vice versa.

Now, comes our hero JQuery.
JQuery can be downloaded from http://docs.jquery.com/Downloading_jQuery#Download_jQuery
HTML

<a id="clickhere" href="#">Click here</a>
<div id="hide_this">Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents Test contents</div>
JQuery code
<script src="jquery-latest.js"></script> <script type="text/javascript">// <![CDATA[
$(document).ready(function()
{
//$('#hide_this').hide();
  $("#clickhere").click(function()
  {
$('#hide_this').toggle('slow');
});
});
// ]]></script>
Explanation:

On the first line, you are including the jQuery library.
<script src="jquery-latest.js"></script>
Then, comes our code. The ready function will start working once the entire page gets loaded.
$(document).ready(function()
Then, when you click on the link, contents in the “hide_this” div will be shown. Again clicking on the same link, it toggles it action. Also, it comes with animated effect, that you could enjoy.
$("#clickhere").click(function()
{
$(‘#hide_this’).toggle(’slow’);
});
Note: if you need to hide the contents, while the page is getting loaded, you can uncomment the below line in jquery.
//$(‘#hide_this’).hide();
In Javascript, you can modify the HTML code as
<div id="testfooter" style="display: none;">This is foo</div>

Changing Timezone in php configuration file

How can I change the time zone? A simple solution is to modify the value in the php.ini file.
Open the php.ini file. If you don’t know, where the php.ini file is placed, try using phpinfo file.
<?php
phpinfo();
?>
create a file with the above lines and execute this file in the browser.
Wow..
You get all the info regarding the server , components installed and other info. Always remember, it is vulnerable to display the server info to the end user. You can better delete the file, once you are done.
I gave the below screenshot, to guide you to find the php configuration file (php.ini)

Once you found the file, open in an editor and search for the string “timezone”. There you find the default time zone.
[Date]
; Defines the default timezone used by the date functions
date.timezone =
You can change the time zone, as you wish. You can get the list of timezones in this link
http://in2.php.net/timezones
For example, if you need to change it to costa rica time zone, simply modify the above line as
Date.timezone = ‘America/Costa_Rica’

Uploading problem wmv or mp4 ...??????

Make these changes in your php.ini file


Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
;upload_tmp_dir =

; Maximum allowed size for uploaded files.
upload_max_filesize = 500000M

;change maximum post value ,post_max
post_max =1000M


Some servers may not accept the above settings. In that case, htaccess comes to our rescue.
Create a file named “.htaccess” without quotes and add the below lines
php_value upload_max_filesize 10M
php_value post_max_size 20M
These lines does the same functionality as the above.

Monday, November 1, 2010

Creating image thumbnails with PHP!

If we intend to make an image gallery, and we would like to show the thumbails of the images, it wouldn't be a wise idea to show the original images with their height & width modified in the <img> tag, that would result in low image quality & higher download time. The solution to this problem would be creating thumbnails at the server end and display them instead.
This solution can be approached in two ways, you can create the thumbnails once and for all or create thumbnails everytime at runtime.
For this purpose, I wrote a class which will create the thumbnail.
The Class..
 /*
 *    File        :    thumb.class.php
 *    Description    :    Class for creating thumbnails
 */

class Thumb
 
{
     var 
$filename;
     var 
$img;
     var 
$height;
     var 
$width;
     var 
$ratio 10;
     var 
$oldim;
     var 
$oldh;
     var 
$oldw;


     function 
filename($file/* used for setting filename */
     
{
         
$this->filename $file;
     }

     function 
setRatio($ratio/* used for setting ratio */
     
{
         
$this->ratio $ratio;
     }

     function 
init() /* creates the GD stream */
     
{
         
$this->img imagecreatetruecolor($this->width,$this->height);
     }

     function 
calculateSize() /* to calculate the output size */
     
{
         
//$this->info = getimagesize($this->filename); 

         /* returns height,width,type,attribute */
         
$this->oldim imagecreatefromjpeg($this->filename);
         
$this->oldw imagesx($this->oldim);
         
$this->oldh imagesy($this->oldim);

         
/* code to re-calculate size maintaining the aspect ratio */
         
$this->width = ($this->oldw/100)*$this->ratio;
         
$this->height = ($this->oldh/100)*$this->ratio;

         
$this->init();
         return 
true;
     }

     function 
finish()
     {
         
$this->calculateSize();
 
imagecopyresampled($this->img,$this->oldim,0,0,0,0,$this->width 

  ,$this->height, $this->oldw,$this->oldh);
         
header("Content-Type: image/jpeg");
         
imagejpeg($this->img);
     }
 }  

--------------------------------------- -----------------------------------------------------------------
An Example:

<?
 
require_once("thumb.class.php");

 
$im = new Thumb;
 
$im->filename("abhishek.jpg");
 
$im->setRatio(10);
 
$im->finish();

 
?>