July 18, 2007

Check if connected to internet

Once I stuck with a problem that "How to check if connected to internet or not using JavaScript"
There could be different reasons for this kind of need.

1. Suppose one need to call an online script from JavaScript code
2. Start downloading a file etc

  1. if(there is NO internet connectivity){
  2. window.close();
  3. }
  4. else{
  5. Call a script OR download a file etc
  6. }


Solution is very simple. Simply Put an image tag in your HTML file and write code like this:

  1. <img src="online-site-url/image.gif" onError="alert('Image missing or no internet connection')">


I hope it will help you guys.

July 3, 2007

Delete Duplicate records

The scenario is:

The table has 3 columns, A, B, and C. Column A is unique for all rows
but the columns B and C can be duplicate across rows.
And it needs to remove the rows where B and C are duplicated.

DELETE
FROM tbl_name
WHERE
a NOT IN
(
SELECT
MIN(a)
FROM daTable
GROUP BY b,c
)

May 31, 2007

Return Selected checkbox values

  1. public Hashtable returnGridSelectedIds(GridView gv1, string chkBoxField)
  2. {
  3. string Id = "";
  4. Hashtable ht = new Hashtable();
  5. if (gv1.Rows.Count > 0)
  6. {
  7. foreach (GridViewRow gvr in gv1.Rows)
  8. {
  9. HtmlInputCheckBox htmChkBox = (HtmlInputCheckBox)gvr.FindControl(chkBoxField);
  10. if (htmChkBox.Checked)
  11. Id += htmChkBox.Value + ",";
  12. }
  13. }
  14. if (Id.ToString() != "")
  15. Id = Id.Substring(0, Id.Length - 1);
  16. ht["Ids"] = Id;
  17. return ht;
  18. }

May 24, 2007

Truncate a string without breaking a word

function truncate_str($string, $length = 80, $etc = '...',$break_words = false)
{
if ($length == 0)
return '';
if (strlen($string) > $length) {
$length -= strlen($etc);
if (!$break_words)
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
return substr($string, 0, $length).$etc;
} else
return $string;
}

April 30, 2007

To chek your link on other site

Check Reciprocal linking:

function
check_backlink($remote_url, $link) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 9);
$data = curl_exec($ch);

if (
curl_errno($ch)) {
return
'URL not working';
} else {
if (
eregi($link, $data)) return 'Found'; else return 'Not Found';
}
curl_close($ch);
}

March 29, 2007

Run Time Image Thumbnail

This code can be used to create Dynamic Image thumbnails on the fly
i.e. You need not to bother about the actual image size while uploading. Just show the desired scaled image anywhere on your website. Same image may need to display in different size on different web-page.


/********** (thumb.php) ****************/
$img=$_GET['img']; $w=$_GET['w']; $h=$_GET['h'];
if(!defined('DIR_CACHE'))
define('DIR_CACHE', './image_cache/');

if (!Is_Dir(DIR_CACHE))
mkdir(DIR_CACHE, 0777);

#IMAGE RESIZE AND SAVE TO FIT IN $new_width x $new_height
if (file_exists($img))
{
$thumb=strtolower(preg_replace('/\W/is', "_", "$img $w $h"));
$changed=0;

if(!is_file($img))
$img = "images/product-image.jpg";

if (file_exists($img) && file_exists(DIR_CACHE.$thumb))
{
$mtime1=filemtime(DIR_CACHE.$thumb);
$mtime2=filemtime($img);
if ($mtime2 > $mtime1)
$changed=1;
}
elseif (!file_exists(DIR_CACHE.$thumb))
$changed=1;

if ($changed)
{
$filename=$img;
$new_width=(int)@$w;
$new_height=(int)@$h;
$lst=GetImageSize($filename);
$image_width=$lst[0];
$image_height=$lst[1];
$image_format=$lst[2];

if ($image_format==1)
$old_image=imagecreatefromgif($filename);
elseif ($image_format==2)
$old_image=imagecreatefromjpeg($filename);
elseif ($image_format==3)
$old_image=imagecreatefrompng($filename);
else
exit;

if (($new_width!=0) && ($new_width < $image_width))
{
$image_height=(int)($image_height*($new_width/$image_width));
$image_width=$new_width;
}

if (($new_height!=0) && ($new_height < $image_height))
{
$image_width=(int)($image_width*($new_height/$image_height));
$image_height=$new_height;
}

$new_image=ImageCreateTrueColor($image_width, $image_height);
$white = ImageCopyResampled($new_image, $old_image, 0, 0, 0, 0, $image_width, $image_height, imageSX($old_image), imageSY($old_image));
#ImageFill($new_image, 0, 0, $white);
imageJpeg($new_image, DIR_CACHE.$thumb);
}

header("Content-type:image/jpeg");
readfile(DIR_CACHE.$thumb);
}
/********** CODE END ****************/

Here is the example use
< img src="thumb.php?img=image1.jpg?w=150&h=100" >

Tricky & nice :
If a thumbnail of a particular size of an image is created, script will not create the dynamic thumbnail again. It will pick that thumb from image_cache folder, if already exists.

note: "image_cache" folder requires 777 permission

March 26, 2007

Reading site content using CURL

For reading content of a website in PHP, there are lot of different ways & functions available like:
$site_content=file($url); #OR
$site_content=file_get_contents($url) ;

But these functions does not work in some server environments where "allow_url_fopen" is off in php.ini & you don't have permission to change this.
You can use the following alternative (using CURL) in that case.

$url="http://www.bestenough.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$store = curl_exec ($ch);
curl_close ($ch);
echo($store);

March 15, 2007

Website Shifting (All files & DataBase)

Here is the method for Shifting your website & database from one server to another with simple steps. This works only on Linux server.

Steps to follow on Existing(Source) Server:
1. Move in the root folder of project i.e. change the directory
cd /path/to/dir

2. Compress the website(project) folder
tar -cvf xxxx.tar * (Supposing 'xxxx' is the name of project)

3. Export the Database in a tar file
mysqldump dbName -u dbUserName -p > dbFileName.tar
Password: myPassword

example:
mysqldump xxxx -u root -p > xxxx_DB_Backup.tar
Password: password

4. Copy the tar files to New server, where you want to shift (move) the website
scp xxxx.tar RemoteUserName@RemoteIP:/path/to/dir/xxxx.tar
Password: (password for that user of Remote IP)

example:
scp xxxx.tar root@127.0.0.1:/home/xyz/public_html/xxxx.tar
Password: myRootPassword

scp xxxx_DB_Backup.tar root@127.0.0.1:/home/xyz/public_html/xxxx_DB_Backup.tar
Password: myRootPassword

Steps to follow onNew(Target) Server:
1. Move in the root folder of project, where you have copied the compressed file
cd /path/to/dir

2. UnTar the tar file
tar -xvf xxxx.tar

3. Import the Database
mysql myDbName -u
dbUserName -p < dbFileName.tar
Password: myPassword

March 14, 2007

Full Backup of MySQL DataBase

Here are some methods for FULL backup of MySQL Databases. This way all the constraints, stored procedures, triggers etc will be copied for backup and/or replicating the database.

Depending on your access to server, you can choose the different options.
e.g. you will not be able to copy the files from a shared hosting server (Method 3)

METHOD 1:
shell> mysqldump --tab=/path/to/some/dir --opt --full

METHOD 2:
shell> mysqlhotcopy database /path/to/some/dir

METHOD 3:
simply copy all table files (`*.frm', `*.MYD', and `*.MYI' files)

METHOD 4:
You can write your own script which you can use to backup your database with various options. An example script can be downloaded from here

Please comment to this post to suggest more methods which can be added here.
Thanks

February 23, 2007

Show Hide elements

Here are some JavaScript Functions for Showing or Hiding block(s) of HTML elements on any javascript event like: onClick, onMouseOver, onBlur etc etc...

These functions can be used to make good effects on the HTML pages.
These functions are Browser compatible, To use, you just need to pass the ID(s) of the elements(s) you want to show/hide with some event on client side.


Alter Display: It checks the current display status of the element with the ID passes, and alters that. If element is displaying on screen, it will be hide and vice-versa.
//input -> ID of the HTML element (DIV, SPAN, TABLE, TR etc)
function alterDisplay(id)
{
if(document.getElementById(id))
{
e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = "";
else
e.style.display = "none";
}
}


hideIDs(): This function hides all the IDs passed in one go.
It accepts the multiple IDs in comma separated form.
Note: Input is one string only, there is no space between comma (,) & ID
//input -> comma separated IDs of the HTML element (DIV, SPAN, TABLE, TR etc)
//e.g. 1 -> hideIDs('div1,div2,tr1'); //Multiple IDs
//e.g. 2 -> hideIDs('div1'); //Single ID

function hideIDs(IDs)
{
var IDs = IDs.split(',');
for(i=0;i < IDs.length;i++)
{
e = document.getElementById(IDs[i]);
e.style.display = "none";
}
}

showHiddenIDs():
This function shows (un-hide) all the IDs passed in one go. It accepts the multiple IDs in comma separated form.

Note: Input is one string only, there is no space between comma (,) & ID
//input -> comma separated IDs of the HTML element (DIV, SPAN, TABLE, TR etc)
//e.g. 1 -> showHiddenIDs('div1,div2,tr1'); //Multiple IDs
//e.g. 2 -> showHiddenIDs('div1'); //Single ID

function showHiddenIDs(IDs)
{
var IDs = IDs.split(',');
for(i=0;i < IDs.length;i++)
{
e = document.getElementById(IDs[i]);
e.style.display = "";
}
}

February 22, 2007

Print This Page

This JavaScript function is very useful where we have "Print this page" button.
Example: Print your invoice

Conventionally, the logic for implementing the functionality is:
1. Whole of the page is displayed [with a button(Print) on top/bottom ]
2. This generated page could be a Static HTML page, or a Dynamic page(Created in scripting language like PHP, ASP, C#.net etc).
3. On clicking on "Print" button, a new window(or pop-up) is opened, where full code for generating the same HTML (for required part of page) is written again.
4. Then page is printed.

With this function, You just need to:
1. Have all the required part (needed to print) into a DIV tag.
2. OnClick of the "Print" Button call this function & pass the ID of DIV tag.
3. It's done :)

function PrintThisPage(print_div_id)
{
var popup_content = document.getElementById(print_div_id).innerHTML;
var sOption="toolbar=yes,location=no,directories=yes,menubar=yes,";
sOption+="scrollbars=yes,width=620,height=460,left=100,top=25";

var winprint=window.open("","",sOption);
winprint.document.open();
winprint.document.write(popup_content);

winprint.print();
winprint.document.close();
winprint.focus();
}

This is tested in Mozilla FireFox, Internet Explorer.
Hopefully it will work in all other browsers too.

Random Password

This function returns you the Random password (text) of the required length. Default password length is given 8. This function is useful to give a temporary password, in case of 'User Registeration' and/or 'Forgot password'


function getRandomPassword($length=8)
{
$chars = "abcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 1;
$pass = '' ;

#Default: 8 digit password
while ($i <= $length)
{
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;}
return $pass;
}

February 21, 2007

Make Clickable Links

This is very small & useful function that finds & converts all the Email text, URL text to a clickable text. You just need to pass the full text & use the returned text.

Here is the code & usage example


### Use: To convert text parts(Email address, URLs) to clickable text
### Author: Akash Dwivedi
### Date: 27 June 2005

  1. function makeClickableLinks($text)
  2. {
  3. $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
  4. '\\1">\\1', $text);
  5. $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
  6. '\\1\\2">\\2', $text);
  7. $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
  8. '\\1">\\1', $text);
  9. return $text;
  10. }

# Example Usage
#Email address example
$text = "Mail me: you@example.com";
echo makeClickableLinks($text);

# URL example
$text = "My URL is: http://www.tech-akash.blogspot.com";
echo makeClickableLinks($text);

# FTP URL example
$text = "FTP is: ftp://ftp.example.com Here is the trailing text";
echo makeClickableLinks($text);
?>

I hope this is useful.

SQL Server 2000 Vs MYSQL v4.1 ( Limits)

Here you can find comparison of Limits.. between 'SQL Server 2000' & 'MySQL 4.1'


Feature SQL Server 2000 MySQL 4.1
column name length 128 64
index name length 128 64
table name length 128 64
max indexes per table 250 32
index length 900 1024
max index column length 900 255
columns per index 16 16
max char() size 8000 1048543
max varchar() size 8000 1048543
max blob size 2147483647 1048543
max number of columns in GROUP BY Limited only by number of bytes (8060) 64
max number of columns in ORDER BY Limited only by number of bytes (8060) 64
tables per SELECT statement 256 31
max columns per table 1024 2599
max table row length 8036 65534
longest SQL statement 16777216 1048574
constant string size in SELECT 16777207 1048565