Flipkart

Wednesday, March 31, 2010

Beginning SSH on Ubuntu

Installing OpenSSH

The Ubuntu (and MacOS X) flavor of SSH is called OpenSSH, a free, open-source implementation of the ssh protocol. It consists of two basic components, an openssh-client and an openssh-server. SSH clients communicate with SSH servers over encrypted network connections.

The openssh-client software should already be installed by default on Ubuntu. If you want to be able to accept SSH connections as well as request them, you’ll need the server software as well. The easiest way to ensure you have both is simply to run:

sudo apt-get install openssh-client openssh-server

Using SSH to Log into a Remote Computer

Once OpenSSH is installed, you can login to a remote SSH server by using the ssh command:

ssh remoteuser@remotebox

where remoteuser is the username of the remote account you’re trying to access, and remotebox is the remote server’s hostname or IP address.

For example, if you know that your Kubuntu desktop box (now running openssh-server) has a user account named joebanks and that the IP address of that computer on your private LAN is 192.168.0.12, you could login remotely to that account from your Linux/Mac laptop by typing:

ssh joebanks@192.168.0.12

If you’re unsure of a computer’s local IP address, try running ifconfig on that machine. This will display the status of the active network interfaces, and the local IP address of that device will be listed after inet addr. It will most likely be in the form of 192.168.0.xx.

Or, if you’ve got a web hosting account that allows shell access (e.g., DreamHost) with a domain name like cooldomain.com, your syntax might look like:

ssh joebanks@cooldomain.com

Now, the first time an SSH client encounters a new remote server, it will report that it’s never seen the machine before, by printing the following message:

The authenticity of host 'remotebox (192.168.0.12)' can't be established.
RSA key fingerprint is 53:b4:ad:c8:51:17:99:4b:c9:08:ac:c1:b6:05:71:9b.
Are you sure you want to continue connecting (yes/no)?

This is just an extra security measure to ensure that you’re actually connecting to the machine you think you are. If you type yes (the most common response), you’ll see the following:

Warning: Permanently added 'remotebox' (RSA) to the list of known hosts.

Subsequent login attempts to this machine will omit the warning message. You’ll then be asked for the remoteuser’s password:

remoteuser@remotebox's password:

And after correctly entering it, like magic, you’ll be logged into the remote machine, and instead of your local machine’s command prompt, you’ll see the following:

remoteuser@remotebox:~$

And, voila! You can execute commands on the remote machine just as you would on your local box. To close the connection to the remote server, type exit, or use Ctrl-D.

Copying Files

To transfer files and directories from your local machine to the remote server and vice-versa, you’ll use SSH’s “secure copy” command, or scp. To copy a single file from your local machine to the server, use the following syntax:

scp file.txt remoteuser@remotebox:/directory

where file.txt is the name of a file in the current directory of your local machine, remoteuser@remotebox is the username and hostname or IP address of the server (just like in the above ssh examples, and /directory is the directory path on the server where you want your file copied.

For example, if you want to copy the local file.txt to the /home/joebanks/docs directory on the server you logged into above, you’ll run the following command from a local terminal session:

scp file.txt joebanks@192.168.0.12:/home/joebanks/docs



You can be as verbose as you want with the local and remote filenames and directories, even changing the filename in the process, like so:

scp ~/docs/oldfile.txt joebanks@192.168.0.12:/home/joebanks/docs/newfile.txt

To copy a file from the server to your local machine, use the following syntax:

scp remoteuser@remotebox:file.txt /local/directory

where remoteuser@remotebox is the username and hostname or IP address of the server, file.txt is a file in the /home/remoteuser directory, and /local/directory is the local directory path into which the file will be copied.

Again, you can be as verbose as necessary, for example:

scp joebanks@192.168.0.12:~/docs/newfile.txt /home/joe/downloads

Copying Directories

To copy an entire directory (and all of its contents) from the local machine to the remote server, use the recursive -r switch, like so:

scp -r /local/directory remoteuser@remotebox:/remote/directory

where /local/directory is the path to the local directory you want copied, and /remote/directory is the remote directory into which you want the directory to be copied.

To copy an entire directory (and all of its contents) from the remote server to the local machine, use the following:

scp -r remoteuser@remotebox:/remote/directory /local/directory

where /remote/directory is the path to the remote directory you want copied, and /local/directory is the local directory into which you want the directory to be copied.

Tuesday, March 30, 2010

PHPMyAdmin Installation on Fedora

Step One
To install PHPMyAdmin using yum, simply issue
# yum -y install phpMyAdmin.noarch
Step Two
PHPMyAdmin Security Access
By default installation, phpmyadmin administration page can only be accessed from localhost via web browser for added security. If you wish to access phpmyadmin page from multiple hosts, modify phpmyadmin conf page as shown below
# vi /etc/httpd/conf.d/phpMyAdmin.conf
and edit the necessary settings. For example, if you require phpmyadmin web page to be accessible from a computer host with an IP address of 123.123.123.123, edit phpMyAdmin.conf to reflect the below similar lines
#order deny,allow
#deny from all
Allow from All
allow from 127.0.0.1
allow from 123.123.123.123


and next add the Allow from All Line
< Directory /usr/share/phpMyAdmin/libraries >
   Order Deny,Allow
   Allow from All
< /Directory>
Save, exit and reload apache web server.
# service httpd restart

Thursday, March 25, 2010

Enable mode_rewrite module in xampp

If you running XAMPP on Windows and unable to figure out how to enable mod_rewrite in apache then here is the solution and it is very simple

Search for httpd.conf file in xampp folder it should be located at xampp/apache/conf and open file in any editor and search for below line:

#LoadModule rewrite_module modules/mod_rewrite.so

and just remove the "#" symbol then it will be like

LoadModule rewrite_module modules/mod_rewrite.so

Next, search for "AllowOverride None" and change it to "AllowOverride All". It is correct once and wrong twice in the file.

Once you have made these changes, save httpd.conf file and restart Apache for mod_rewrite to take effect.

Tuesday, March 23, 2010

Iframe Popup's

<span style="color: #330099; font-weight: bold;">This is the Ifram panel which has to be written in Aspx page or Masterpage</span>

<asp:panel borderstyle="None" id="pnlPopup" runat="server" style="display: none;">
<iframe frameborder="0" id="ifrmPopup" runat="server" style="border: 0pt none; height: 500px; width: 800px;"></iframe>
</asp:panel>
<ajaxtoolkit:modalpopupextender backgroundcssclass="modalpopupclass" id="mpePopup" popupcontrolid="pnlPopup" runat="server" targetcontrolid="hdnMPE">
</ajaxtoolkit:modalpopupextender>
<asp:button id="hdnMPE" runat="server" style="display: none;">


<span style="color: #330099; font-weight: bold;">===  Script for opening popup  ====</span>

<script language="javascript" type="text/javascript">
function funPopup(id) {

var frm = document.getElementById('ctl00_ContentPlaceHolder1_ifrmPopup');
frm.src = "../ModalPopups/Delete.aspx"; <span style="color: rgb(51, 0, 153);"> (Your page URL which has to be opened)</span>
frm.style.height = "220px";
frm.style.width = "750px";
var obj1 = $find('ctl00_ContentPlaceHolder1_mpePopup');
if (obj1 != null) {
obj1.show();
}
return false;
}
</script>

================  Popup css ==================

.modalpopupclass
{
background-color:Gray;
filter:alpha(opacity=40);
opacity:0.4;
}


================ Add in webConfig  ============

<add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit">



================ Method to call for image ===========


<asp:imagebutton id="img" imagealign="Middle" imageurl="~/Images/Image.gif" runat="server">

===============  .cs (Page Load)  ===========

imgDelete.Attributes.Add("onclick", "javascript:return funPopup()");


<span style="color: #330099; font-weight: bold;">=====For closing popup (this has to be written in popup.aspx page)====== </span>

<script language="javascript" type="text/javascript">
function funPopupClose() {
window.parent.document.getElementById('ctl00_ContentPlaceHolder1_ifrmPopup').src = "";
var objF = window.parent.$find('ctl00_ContentPlaceHolder1_mpePopup');
objF.hide();
//window.parent.document.forms[0].submit();
return false;
}
</script></asp:imagebutton></add></asp:button>

Free Google Gadgets For Your Website

Here you can find the Gadgets from Goolgle which you can integrate in website very easily.

Monday, March 22, 2010

Create Multisite in Drupal

To create multisite in drupal we need to change hosts configuration file as follows:
Windows/System32/drivers/etc/hosts (for windows)
And add new line like
127.0.0.1 loclahost
127.0.0.1 subdomain

after that just craete a folder called subdomian in drupal6/sites, then copy the settings.php file in newly created folder.Once done all the above steps Just type the URL like http;//subdomain/drupal6 in your browser then it will install new site.

If you want to create a url like just http://subdomain then you need create the Virtualhost in httpd.conf file like,


< VirtualHost *:80 >
DocumentRoot C:/xampp/htdocs/drupal6
ServerName subdomain

< /VirtualHost >

Backup Mysql Database From Commandline

 Backing up your database is something you should do often. Like most things, there are a lot of ways to do this, but using the command-line is one of the best. Why? Because it helps you get around potential problems like execution timeouts for tools like phpMyAdmin, and potential network dropouts from using a local administration tool like MySQL Workbench.



mysqldump -h localhost -u username -p database_name > backup_db.sql

take a backup in compress mode:

mysqldump -u username -h localhost -p database_name | gzip -9 > backup_db.sql.gz

(OR) 

mysqldump -u username -p database_name | gzip -c backup.sql.gz 

Now, to explain what’s going on here! The “mysqldump” program is a tool for creating database backups. The parameters being used are:
  • “-u” switch means you’re going to specify a username to connect with, which must follow, like “-u mysqluser” above
  • “-p” switch means you’re either going to immediately specify the password to use (with no space), or it’ll prompt you for one
  • The final parameter used in the example above is the name of the database to backup (of course!)
If you ran the command above, you would’ve seen the contents of your database go whizzing by on the screen. That’s good, because we know that part works (actually connecting to the database), but it’s also bad, because… where did it go? Answer: nowhere! It scrolled past, and that was it. Now we need to capture it and put it in a file.
To place the contents of the output into a file, for back-up purposes, we need to use what’s called a redirection.


 

Convert Array to XML format

function print_r_xml($arr,$wrapper="data",$cycle = 1)
{
   
    //useful vars
    $new_line = "\n";

    //start building content
    if($cycle == 1) { $output = '<\?xml version="1.0" encoding="UTF-8" ?>'.$new_line; } 
    $output.= tabify($cycle - 1)."<".$wrapper.">".$new_line;
    foreach($arr as $key => $val)
    {
        if(!is_array($val))
        {
            $output.= tabify($cycle).'<'.htmlspecialchars($key).'>'.$val.'</'.htmlspecialchars($key).'>'.$new_line;
        }
        else
        {
            $output.= print_r_xml($val,$key,$cycle + 1).$new_line;
        }
    }
    $output.= tabify($cycle - 1).'</'.$wrapper.'>';

    //return the value
    return $output;
}

/* tabify */
function tabify($num_tabs)
{
    for($x = 1; $x <= $num_tabs; $x++) { $return.= "\t"; }
    return $return;
}


/* test */
$_POST = array(
                'first_name'=>'Faruq',
                'last_name'=>'Shaik',
                'url'=>'http://faruq1256.blogspot.com',
                'languages'=>array('php','javascript','Python','Ruby'),
                'title'=>'Web Developer',
                'favorite'=>array('PHP'=>'http://php.net','Jquery'=>'http://jquery.com')
            );
echo print_r_xml($_POST);

Thursday, March 18, 2010

Take Full Backup From cPanel By PHP Script

Make one php file and give it to name whatever you want like details_cp.php, this file is just for details of your cPanel and FTP and other things. So the content of details_cp.php would be given below

<?php
$cpuser = “cpanel username”; //cPanel Username
$cppass = “cpanel Password”; //cPanel Username
$domain = “yourdomain.com”; // Domain name you want to take backup
$skin = “x2″; // no need to change

$ftpuser = “FTP username”; // FTP username
$ftppass = “FTP password”; // FTP username
$ftphost = “FTP host”; // FTP Host
$ftpmode = “passiveftp”;
$ftpdir = “/subdir”;

$notifyemail = “webmaster@mydomain.com”; // Email which will use in case of any error.

$delbackup = 1;

$secure = 0; // If you are using secure ssl connection

$debug = 0;
?>



After that you have to create second file, which is then main backup script,

<?php
include(‘details_cp.php’);
if ($secure) {
$url = “ssl://”.$domain;
$port = 2083;
} else {
$url = $domain;
$port = 2082;
}

if ($delbackup) {
$conn_id = ftp_connect($ftphost);
if ($conn_id) {
$ok = ftp_login($conn_id, $ftpuser, $ftppass);
if ($ok) {
if (!empty($ftpdir)) {
$ok = ftp_chdir($conn_id,$ftpdir);
}
if ($ok) {
$dirlist = ftp_nlist($conn_id, “backup*”);
if (!empty($dirlist[0])) @ftp_delete($conn_id,$dirlist[0]);
}
}
ftp_close($conn_id);
}
}

$socket = fsockopen($url,$port);
if (!$socket) { echo “Cannot connect to $url\n”; exit; }
$authstr = $cpuser.”:”.$cppass;
$pass = base64_encode($authstr);
$request_data = “dest=”.urlencode($ftpmode).”&email=”.urlencode($notifyemail);
$request_data .= “&server=”.urlencode($ftphost).”&user=”.urlencode($ftpuser);
$request_data .= “&pass=”.urlencode($ftppass);
if (!empty($ftpdir)) $request_data .= “&rdir=”.urlencode($ftpdir);
$request_data .= “&submit=”.urlencode(‘Generate Backup’);

fputs($socket,”POST /frontend/”.$skin.”/backup/dofullbackup.html HTTP/1.1\r\n”);
fputs($socket,”Host: $domain\r\n”);
fputs($socket,”Authorization: Basic $pass\r\n”);
fputs($socket,”Content-type: application/x-www-form-urlencoded\r\n”);
fputs($socket,”Content-length: “.strlen($request_data).”\r\n\r\n”.$request_data);

while (!feof($socket)) {
$response = fgets($socket,4096);
if ($debug) echo $response;
}
fclose($socket);
?>


Then upload these to files and just run backup_cp.php it will create the .zip file in our root directory

Tuesday, March 16, 2010

Jquery: Ajax Function

$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});

for more detailed Information:
http://api.jquery.com/jQuery.ajax/

Monday, March 15, 2010

JS:Bookmark & Share Widget

< a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&username=xa-4b9df5e0641b728d">< img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0" />

For more Information:
http://www.addthis.com/

Thursday, March 11, 2010

Google API: Add a YouTube Video to Your Web Site

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1">
</param><param name="allowFullScreen" value="true">
</param><param name="allowscriptaccess" value="always">
</param><embed src=http://www.youtube.com/v/GwQMnpUsj8I&hl=en&fs=1
type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344">
</embed></object>

for more details:
http://code.google.com/apis/youtube/player_parameters.html

Google API: An AJAX Currency Converter

<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<!-- when using Google to load JSON API -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="http://www.geoplugin.net/ajax_currency_converter.gp" type="text/javascript"></script>
<!-- When using your own JSON API -->
<!-- <script src="http://www.geoplugin.net/ajax_currency_converter.gp?nogoog=1" type="text/javascript">
</script> -->
<input type='text' id='gp_amount' size='4' />
<select id="gp_from"></select> to <select id="gp_to"></select>
<p><input type='button' onClick='gp_convertIt()' value = 'Convert It' /></p>
<div id="gp_converted"></div>
<script>gp_currencySymbols()</script>

For more information:
Geolocation by geoPlugin

Google API: Embedding a Google Map

<html>
 <head>
  <script src="http://maps.google.com/maps?file=api&v=2&key=Your_Google_Maps_API_Key" type="text/javascript"></script>
  <script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
 
  <script type="text/javascript">
    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(geoplugin_latitude(), geoplugin_longitude()), 12);
      }
    }
  </script>
 </head>
 <body>
   <div id="map" style="width: 500px; height: 300px"></div>
   <script>load();</script>
 </body>
</html>

Google API: Your own personalized weather forecast

This code requires the ParseXml class.
 
<?php
 
$geoplugin = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
 
if ( is_numeric($geoplugin['geoplugin_latitude']) && is_numeric($geoplugin['geoplugin_longitude']) ) {
 
    $lat = $geoplugin['geoplugin_latitude'];
    $long = $geoplugin['geoplugin_longitude'];
    //set farenheight for US
    if ($geoplugin['geoplugin_countryCode'] == 'US') {
        $tempScale = 'fahrenheit';
        $tempUnit = '&deg;F';
    } else {
        $tempScale = 'celsius';
        $tempUnit = '&deg;C';
    }
    require_once('ParseXml.class.php');
 
    $xml = new ParseXml(); 
    $xml->LoadRemote("http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query={$lat},{$long}", 3);
    $dataArray = $xml->ToArray();
 
    $html = "<center><h2>Weather forecast for " . $geoplugin['geoplugin_city'];
    $html .= "</h2><table cellpadding=5 cellspacing=10><tr>";
 
    foreach ($dataArray['simpleforecast']['forecastday'] as $arr) {
 
        $html .= "<td align='center'>" . $arr['date']['weekday'] . "<br />";
        $html .= "<img src='http://icons-pe.wxug.com/i/c/a/" . $arr['icon'] . ".gif' border=0 /><br />";
        $html .= "<font color='red'>" . $arr['high'][$tempScale] . $tempUnit . " </font>";
        $html .= "<font color='blue'>" . $arr['low'][$tempScale] . $tempUnit . "</font>";
        $html .= "</td>";
 
 
    }
    $html .= "</tr></table>";
 
    echo $html;
}
 
?>

Wednesday, March 10, 2010

Drupal Pagination using pager_query()

This is the simplest pagination method using pager theme in Drupal, we can customize the links using pagination.inc file in includes folder also.

$limit = 7;
$query = "select nid,title from {node} where type='event'";
$count = "select count(*) from {node} where type='event'";

  $result = pager_query($query, $limit , 0, $sql_count);
  $output .= theme('pager', NULL, $items_per_page, 0);


GROUP BY

Queries with GROUP BY clauses need special care. Copied from the documentation on pager_query:

Unfortunately, the rewrite rule does not always work as intended for queries that already have a "COUNT(*)" or a "GROUP BY" clause, and possibly for other complex queries. In those cases, you can optionally pass a query that will be used to count the records. For example, if you want to page the query "SELECT COUNT(*), TYPE FROM node GROUP BY TYPE", pager_query() would invoke the incorrect query "SELECT COUNT(*) FROM node GROUP BY TYPE". So instead, you should pass "SELECT COUNT(DISTINCT(TYPE)) FROM node" as the optional $count_query [fourth] parameter.

Google API: Google Charts

You basically just call the Google Chart URL within your src property with the appropriate parameters and Google Chart will draw up the graph and show it to you as a png image type.



< img src="http://chart.apis.google.com/chart?cht=p3&chd=s:hW%3Cbr%3E&chs=250x100&chl=Hello%7CWorld" />


It will create the Pie chart.

By Using Google Charts API you can generate Line chart,Venn diagram,Bar chart etc...

You can find the complete documentaion from google here

Linux: Basic Linux Commands

mkdir - make directories
Options
Create the DIRECTORY(ies), if they do not already exist.
 Mandatory arguments to long options are mandatory for short options too.
 -m, mode=MODE  set permission mode (as in chmod), not rwxrwxrwx - umask
 -p, parents  no error if existing, make parent directories as needed
 -v, verbose  print a message for each created directory
 -help display this help and exit
 -version output version information and exit

mv- change the name of a directory
Type mv followed by the current name of a directory and the new name of the directory.
 Ex: mv testdir newnamedir 


pwd - print working directory
will show you the full path to the directory you are currently in. This is very handy to use, especially when performing some of the other commands on this page


chmod - change file access permissions
 Ex: chmod -r 777 filename
r  Change the permission on files that are in the subdirectories of the directory that you are currently in.        permission  Specifies the rights that are being granted. Below is the different rights that you can grant in an alpha  numeric format.filenames  File or directory that you are associating the rights with Permissions



cp - Copy files
cp  myfile yourfile
 
Copy the files "myfile" to the file "yourfile" in the current working directory. This command will create the file "yourfile" if it doesn't exist. It will normally overwrite it without warning if it exists.
 
   
cmp file1 file2 -  
Compares two files, reporting all discrepancies. Similar to the diff command, though the output format differs.




find path -name pattern -print
Searches the specified path for files with names matching the specified pattern (usually enclosed in single quotes) and prints their names. The find command has many other arguments and functions; see the online documentation.
Ex: find dir -name index.html 


kill process_ids
kill - signal process_ids
kill -l
Kills the specified processes, sends the specified processes the specified signal (given as a number or name), or prints a list of available signals.

MySQL date calculations

select domain, count(*) as cnt from referrers where date >= current_date()-2 group by domain order by cnt;


Simple Date Calculations
Date calculations are relatively easy. The first function we're going to look at is the YEAR() function, which returns a year from a given date. For example:

mysql> SELECT YEAR('2003-03-31');
+--------------------+
| YEAR('2003-03-31') |
+--------------------+
| 2003 |
+--------------------+

We can perform simple arithmetic on a date using the '+' and '-' operators. For example, to find out which year is five years ahead of a given date, you can use:
mysql> SELECT YEAR('2003-03-31')+5;
+----------------------+
| YEAR('2003-03-31')+5 |
+----------------------+
| 2008 |
+----------------------+

And to find out which year was five years in the past:
mysql> SELECT YEAR('2003-03-31')-5;
+----------------------+
| YEAR('2003-03-31')-5 |
+----------------------+
| 1998 |
+----------------------+

Of course you don't have to hard-code the date. MySQL is quite capable of telling the date and time, using the NOW() function:
mysql> SELECT NOW();
+---------------------+
| NOW() |
+---------------------+
| 2003-03-31 00:32:21 |
+---------------------+

or just the date with the CURRENT_DATE() function:
mysql> SELECT CURRENT_DATE();
+----------------+
| CURRENT_DATE() |
+----------------+
| 2003-03-31 |
+----------------+

There are also functions for the other date and time intervals; MONTH(), DAYOFMONTH(), HOUR(), MINUTE() and SECOND(). For example:
mysql> SELECT MONTH(NOW()) AS m,
DAYOFMONTH(NOW()) AS d,
HOUR(NOW()) AS h,
MINUTE(NOW()) AS m,
SECOND(NOW()) AS s;
+------+------+------+------+------+
| m | d | h | m | s |
+------+------+------+------+------+
| 3 | 31 | 1 | 53 | 38 |
+------+------+------+------+------+

The DAYOFMONTH() function is an exception to the naming conventions because there are a number of other ways to return the day. DAYOFMONTH() returns the day as a numeric from 1 to 31, but there is also DAYNAME() which returns the actual name of the day, DAYOFWEEK() which returns a number from 1 (Sunday) to 7(Saturday) and DAYOFYEAR() returning a number from 1 to 366. Some examples:

mysql> SELECT DAYNAME('2000-01-01');
+-----------------------+
| DAYNAME('2000-01-01') |
+-----------------------+
| Saturday |
+-----------------------+

mysql> SELECT DAYOFWEEK('2000-01-01');
+-------------------------+
| DAYOFWEEK('2000-01-01') |
+-------------------------+
| 7 |
+-------------------------+

mysql> SELECT DAYOFYEAR('2000-12-31');
+-------------------------+
| DAYOFYEAR('2000-12-31') |
+-------------------------+
| 366 |
+-------------------------+



One of the most commonly performed date calculations is one which calculates age. Unfortunately there isn't a function to do it, so you need to do a bit of thinking. Let's begin with doing some simple arithmetic - you can see when I'm running these queries from the earlier results (31 March 2003). First, we'll simply subtract the year of birth from the current year. If you're reading this article well after I wrote it, of course your results may be different:
mysql> SELECT YEAR(CURRENT_DATE)-YEAR('1971-01-01');
+---------------------------------------+
| YEAR(CURRENT_DATE)-YEAR('1971-01-01') |
+---------------------------------------+
| 32 |
+---------------------------------------+

If you were using this to return the age, the result would be correct. Someone born on the 1st of January 1971 would be 32 years old on the 31st of March 2003. But let's test for someone born on the 31st of December:
mysql> SELECT YEAR(CURRENT_DATE)-YEAR('1971-12-31');
+---------------------------------------+
| YEAR(CURRENT_DATE)-YEAR('1971-12-31') |
+---------------------------------------+
| 32 |
+---------------------------------------+

Here the age is wrong. This person would not have turned 32 yet. The problem is that the calculation above only checks the year part of the date. It comes down to subtracting 1971 from 2003, regardless of the month and day. The best way to do this is to compare whether the current month and day are larger than the birth month and day. If it is, a full year has passed, and the year portion of the calculation can be left. If it isn't, a full year hasn't passed, and you need to subtract one from the year portion. It sounds tricky, but it isn't really. Let's break it down slowly. It helps us greatly that MySQL evaluates a true expression to 1, and a false expression to 0. For example:
mysql> SELECT 23>19;
+-------+
| 23>19 |
+-------+
| 1 |
+-------+

mysql> SELECT 23<19;> SELECT RIGHT('abcdef',2);
+-------------------+
| RIGHT('abcdef',2) |
+-------------------+
| ef |
+-------------------+

This returns 2 characters, starting from the right of the string, thus 'ef'. If you ask for more characters than the string is long, MySQL simply returns the whole string:
mysql> SELECT RIGHT('abcdef',9);
+-------------------+
| RIGHT('abcdef',9) |
+-------------------+
| abcdef |
+-------------------+

So, to return the 'MM-DD' portion of a date, you need to return the five rightmost characters, for example:
mysql> SELECT RIGHT(CURRENT_DATE(),5);
+-------------------------+
| RIGHT(CURRENT_DATE(),5) |
+-------------------------+
| 03-31 |
+-------------------------+

Now we have everything we need to calculate an age. The query will have a portion that calculates the difference in years, and then we'll subtract either 0 or 1, depending on the month-day portion. Here is the full query:
mysql> SELECT YEAR(CURRENT_DATE()) - YEAR('1971-12-31')
- (RIGHT(CURRENT_DATE(),5)<'12-31') AS age;
+------+
| age |
+------+
| 31 |
+------+

Tuesday, March 9, 2010

JS:Add/Remove rows from table

Add/Remove dynamic rows in HTML table
<script language="javascript">
        function addRow(tableID) {

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;

            for(var i=0; i<colCount; i++) {

                var newcell    = row.insertCell(i);

                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                //alert(newcell.childNodes);
                switch(newcell.childNodes[0].type) {
                    case "text":
                            newcell.childNodes[0].value = "";
                            break;
                    case "checkbox":
                            newcell.childNodes[0].checked = false;
                            break;
                    case "select-one":
                            newcell.childNodes[0].selectedIndex = 0;
                            break;
                }
            }
        }

        function deleteRow(tableID) {
            try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;

            for(var i=0; i<rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {
                    if(rowCount <= 1) {
                        alert("Cannot delete all the rows.");
                        break;
                    }
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }

            }
            }catch(e) {
                alert(e);
            }
        }

  
</script>


    <input onclick="addRow('dataTable')" type="button" value="Add Row" />

    <input onclick="deleteRow('dataTable')" type="button" value="Delete Row" />

  
<table border="1" id="dataTable">
        <tbody>
<tr>
            <td><input name="chk" type="checkbox" /></td>
            <td><input name="txt" type="text" /></td>
            <td><select name="country">
                    <option value="in">India</option>
                    <option value="de">Germany</option>
                    <option value="fr">France</option>
                    <option value="us">United States</option>
                    <option value="ch">Switzerland</option>
                </select>
            </td>
        </tr>
</tbody></table>

Monday, March 8, 2010

JS:Get all SelectBox Options for adding hidden field

lb = document.form.listbox;
 hiddenfield = document.form.hidden;
 if(hiddenfield.value.length > 0) hiddenfield.value="";

 for (i=0;i < lb.length;i++) {
    if (!isNaN(lb.options[i].value)) {
    if(hiddenfield.value.length > 0)
    hiddenfield.value = hiddenfield.value + "," + lb.options[i].value;
    else
    hiddenfield.value = hiddenfield.value + lb.options[i].value;
    }
 }

Saturday, March 6, 2010

JS: Dynamically add Options in Selectbox

<script>
function addCombo() {
    var textb = document.getElementById("txtCombo");
    var combo = document.getElementById("combo");

    var option = document.createElement("option");
    option.text = textb.value;
    option.value = textb.value;
    try {
        combo.add(option, null); //Standard
    }catch(error) {
        combo.add(option); // IE only
    }
    textb.value = "";
}
</script>

        <fieldset>
            <legend>Combo box</legend>
            Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
            <input type="button" value="Add" onclick="addCombo()">
            <br/>
            Combobox: <select name="combo" id="combo"></select>
        </fieldset>


http://viralpatel.net/blogs/2008/12/dynamic-combobox-listbox-drop-down-using-javascript.html