Thursday, February 28, 2008

Automated MySQL Backups


<?php
$emailaddress 
"XXXXXX@yourdomain.com";
$host="XXXXXX"// database host
$dbuser="XXXXXX"// database user name
$dbpswd="XXXXXX"// database password
$mysqldb="XXXXXX"// name of database
$path "/full_server_path_to_file_goes_here"// full server path to the directory where you want the backup files (no trailing slash)
// modify the above values to fit your environment
$filename $path "/backup" date("d") . ".sql";
if ( 
file_exists($filename) ) unlink($filename);
system("mysqldump --user=$dbuser --password=$dbpswd --host=$host $mysqldb > $filename",$result);
$size filesize($filename);
switch (
$size) {
  case (
$size>=1048576): $size round($size/1048576) . " MB"; break;
  case (
$size>=1024): $size round($size/1024) . " KB"; break;
  default: 
$size $size " bytes"; break;
}
$message "The database backup for " $mysqldb " has been run.\n\n";
$message .= "The return code was: " $result "\n\n";
$message .= "The file path is: " $filename "\n\n";
$message .= "Size of the backup: " $size "\n\n";
$message .= "Server time of the backup: " date(" F d h:ia") . "\n\n";
mail($emailaddress"Database Backup Message" $message"From: Website <>"); 
?>


You can backup all the databases for your user in one backup using the following line in the above script:

system( "mysqldump --all-databases --user=$dbuser --password=$dbpswd --host=$host > $filename",$result);

You can restore a database using the following line in a php script:

system( "mysqldump --user=$dbuser --password=$dbpswd --host=$host $mysqldb < $filename",$result);

Note that hosts may have different paths for the mysql commands.  For example /usr/local/bin/mysqldump could be required.

If you want the backup file to be compressed, then change two lines (the $filename variable and the system() command) as follows:

$filename = "/full_server_path_to_file_goes_here/backup" . $day . ".sql.gz";
system( "mysqldump --user=$dbuser --password=$dbpswd --host=$host $mysqldb | gzip > $filename",$result);

Automated Site Backups

- - Start Script Here - -
<?php
$emailaddress 
"XXXXXX@yourdomain.com";
$path "/full_server_path_to_file_goes_here"// full server path to the directory where you want the backup files (no trailing slash)
// modify the above values to fit your environment
$target $path "/backup" date(d) . ".tar.gz";
if (
file_exists($target)) unlink($target);
system("tar --create --preserve --gzip  --file=".$target." ~/public_html ~/mail",$result);
$size filesize($target);
switch (
$size) {
  case (
$size>=1048576): $size round($size/1048576) . " MB"; break;
  case (
$size>=1024);    $size round($size/1024) . " KB"; break;
  default:               
$size $size " bytes"; break;
}
$message "The website backup has been run.\n\n";
$message .= "The return code was: " $result "\n\n";
$message .= "The file path is: " $target "\n\n";
$message .= "Size of the backup: " $size "\n\n";
$message .= "Server time of the backup: " date(" F d h:ia") . "\n\n";
mail($emailaddress"Website Backup Message" $message"From: Website <>"); 
?>


system("tar --create --preserve --gzip --file=".$target." --exclude ~/public_html/audio ~/public_html ~/mail",$result);

How do I copy a MySQL database from one computer/server to another?

db-name.out

How do I copy a MySQL database from one computer/server to another?

Short answer is you can copy database from one computer/server to another using ssh or mysql client.

You can run all the above 3 commands in one pass using mysqldump and mysql commands (insecure method, use only if you are using VPN or trust your network):
$ mysqldump db-name | mysql -h remote.box.com db-name

Use ssh if you don't have direct access to remote mysql server (secure method):
$ mysqldump db-name | ssh user@remote.box.com mysql db-name

You can just copy table called foo to remote database (and remote mysql server remote.box.com) called bar using same syntax:
$ mysqldump db-name foo | ssh user@remote.box.com mysql bar

This will not just save your time but you can impress your friend too ;). Almost all commands can be run using pipes under UNIX/Linux oses.

$ mysqldump -u root -h localhost -pmypassword faqs | gzip -9 > faqs-db.sql.gz

$ mysqldump -u root -h localhost -pmypassword faqs | gzip -9 > faqs-db.sql.gz

Mysql backup in Easy Ways

Administrating a MySQL server

    Setting the password:


    1. From Unix:
    shell> mysql -u username -h hostname -p password
    mysql> SET PASSWORD FOR username@localhost=PASSWORD('new_password');

    2. Directly manipulate the privilege tables:
    shell> mysql -u username -h host -u username -p
    mysql> UPDATE user SET Password=PASSWORD('new_password') WHERE user='root';
    mysql> FLUSH PRIVILEGES;

    3. Using the mysqladmin command:
    shell> mysqladmin -u username password new_password

    In our case we were able to change password specifying host name along with user name:
    shell> bin/myslqadmin u username h localhost


    MySQL Permissions & Grant Tables


    In order to add a new user or update user's privileges in mysql grant tables login to mysql as a root user.

    There are two options: use GRANT/REVOKE command or manipulating the MySQL grant tables directly.
    The preferred method is to use GRANT statements - more concise and less error-prone.

    If you modify the grant tables manually (using INSERT, UPDATE, etc.), you should execute
    a FLUSH PRIVILEGES statement to tell the server to reload the grant tables.

    To remove user: mysql> delete from user where user='username';
    mysql> FLUSH PRIVILEGES;


    Examples adding a new user with different level of privileges:
    dummy: A user who can connect without a password, but only from the local host.

    mysql> GRANT USAGE ON *.* TO dummy@localhost;

    myUser : A full superuser who can connect to the server from anywhere,
    but who must use a password 'pass' to do so.
    GRANT statements should be for both myUser@localhost and myUser@"%".
    to prevent the anonymous user entry for localhost take precedence.

    mysql> GRANT ALL PRIVILEGES ON *.* TO myUser@localhost
    IDENTIFIED BY 'pass' WITH GRANT OPTION;
    mysql> GRANT ALL PRIVILEGES ON *.* TO myUser@"%"
    IDENTIFIED BY 'some_pass' WITH GRANT OPTION;

    "%" - is a wildcard in mysql. If you are defining your DB table and in the 'host' field
    enter '%', that means that any host can access that database (Of course, that host
    must also have a valid db user).


    admin: A user who can connect from localhost without a password and who is granted
    the RELOAD and PROCESS administrative privileges.
    No database-related privileges are granted.

    mysql> GRANT RELOAD,PROCESS ON *.* TO admin@localhost;


    Add a user that has full rights to his database only but cannot see other database:
    mysql> GRANT USAGE ON *.* TO 'user'@'host' GRANT Select, Insert, Update, Delete,
    Create, Drop ON `database`.* TO 'user'@'host' FLUSH PRIVELEGS;

    The FILE privelege and WITH GRANT OPTION may not be the best way to include, it is
    only in case of creating another superuser with full set of privileges or
    giving privileges to load data using mysql command INLOAD DATA.


    GRANT TABLE FIELDS EXPLANATION:
    TABLE USER: Everything after "password" is a privelege granted with values 'Y' or 'N'.
    This table controls individual user global access rights.

    'host','user','password','select','insert','update','delete','index','alter'
    ,'create','drop','grant','reload','shutdown','process','file'

    TABLE DB: This controls access of USERS to databases.

    'host','db','user','select','insert','update','delete','index','alter',
    'create','drop','grant'

    TABLE HOST: This controls which HOSTS are allowed what global access rights.

    'host','db','select','insert','update','delete','index','alter',
    'create','drop','grant'


    HOST, USER, and DB table are very closely connected - if an authorized USER
    attempts an SQL request from an unauthorized HOST, it is denied.
    If a request from an authorized HOST is not an authorized USER, it is denied.
    If a globally authorized USER does not have rights to a certain DB, it is denied.



    Backups in MySQL


    Full backup of MySql databases:
    1. shell> mysqldump --tab=/path/to/some/dir --opt --full
    OR
    2. shell> mysqlhotcopy database /path/to/some/dir
    OR
    3. simply copy all table files (`*.frm', `*.MYD', and `*.MYI' files)

    For a SQL level backup of a table use SELECT INTO OUTFILE or BACKUP TABLE.

    mysql> BACKUP TABLE tbl_name[,tbl_name...] TO '/path/to/backup/directory'
    Copies to the backup directory the minimum number of table files needed to
    restore the table, after flushing any buffered changes to disk.

    RESTORE TABLE tbl_name[,tbl_name...] FROM '/path/to/backup/directory'
    Restores the table(s) from the backup that was made with BACKUP TABLE.
    Existing tables will not be overwritten; if you try to restore over an existing
    table, you will get an error. Restoring will take longer than backing up due to
    the need to rebuild the index. The more keys you have, the longer it will take.
    Just as BACKUP TABLE, RESTORE TABLE currently works only for MyISAM tables.

    Selective backups can be done with:
    SELECT * INTO OUTFILE 'file_name' FROM tbl_name
    and restore with:
    LOAD DATA INFILE 'file_name' REPLACE ...
    To avoid duplicate records, you need a PRIMARY KEY or a UNIQUE key in the table.
    The REPLACE keyword causes old records to be replaced with new ones when a new
    record duplicates an old record on a unique key value.

    Monitoring tools


    The myisamchk utility is used to get information, check, repair or optimise mysql database tables:
    shell> myisamchk [options] tbl_name

    With no options, myisamchk simply checks the table.

    Some useful Options for myisamchk utility:

    1. Print informational statistics about the table that is checked: -i or --information
    2. Check only tables that have changed since the last check: -C or --check-only-changed
    3. The recommended way to quickly check all tables:
    myisamchk --silent --fast /path/to/datadir/*/*.MYI

    To Start the server automatically at system startup time


    The mysql.server and safe_mysqld scripts can be used to start/stop the server automatically.
    shell> mysql.server start
    shell> mysql.server stop

    See mysql.server in the `share/mysql' directory or in the `support-files' directory of the MySQL source tree.
    The mysql.server script understands the following options: datadir, basedir, and pid-file.

    If your system uses `/etc/rc.local' to start external scripts, you should append the following to it:

    /bin/sh -c 'cd /usr/local/mysql ; ./bin/safe_mysqld --user=mysql &'

    The mysql.server script understands the following options: datadir, basedir, and pid-file.



MysqlDump in Different Way

This is on a Windows 2000 server

From the root directory, backing up a database named "general"

c:/>cd mysql
c:/mysql>cd bin
c:/mysql/bin>mysqldump general > c:/general.sql

This creates a text file in the root directory that contains all the tables and each item in the database.

Using the created text file backup to create the database on a different server:

c:/>mysql
create database general;
Database general created.
use general;
source c:/general.sql

Creating thumbs from textfiles with PHP and GD

Creating thumbs from textfiles with PHP and GD
$width = 80;
$height = 120;
$font = 3; // "3" is a default font in the GD library.


now the next step is getting the text files lines and how many characters from each line we can use.

$lines = file("test.txt");
$fontWidth = imagefontwidth($font);
$fontHeight = imagefontheight($font);
$maxCharsPerLine = ($width / $fontWidth) - 2;
$maxLines = ($height / $fontHeight) - 2;
$lineHeight = $fontHeight + 1;


Ok so we have that all done the next step is to get the image ready.

$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 0, 0, 0);
$black = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);


Now we are ready to start adding text to do this will will just loop through our lines up to our maxLines limit and only use our maxCharsPerLine from each line. We will also replace tab characters with two spaces and remove any carriage return character

for($i = 0; $i < $maxLines; $i++) {
    $line = (strlen($lines[$i]) > $maxCharsPerLine) ? substr($lines[$i], 0, $maxCharsPerLine) : $lines[$i];
    $line = ereg_replace("\t", "  ", $line);
    $line = ereg_replace("\r", "", $line);
    
    imagestring($image, $font, 3, ($i * $lineHeight), $black);
}


We will then add a border to the image. Afterwards you can save your image and you should have a nice image with text from your text file on it.

imageline($image, 0, 0, $width, 0, $black);
imageline($image, ($width - 1), 0, ($width - 1), ($height - 1), $black);
imageline($image, ($width - 1), ($height - 1), 0, ($height - 1), $black);
imageline($image, 0, ($height - 1), 0, 0, $black);

imagepng($image, "test.png");
imagedestroy($image);


and for those of you who just want the function to use here it is.

function FileToThumb($file, $save_path, $font, $width, $height) {
    if(!is_numeric($font)) {
        $fontRes = imageloadfont($font);
    }
    else {
        $fontRes = $font;
    }

    $lines = file($file);
    $fontWidth = imagefontwidth($font);
    $fontHeight = imagefontheight($font);
    $maxCharsPerLine = ($width / $fontWidth) - 2;
    $maxLines = ($height / $fontHeight) - 2;
    $lineHeight = $fontHeight + 1;
 
    $image= imagecreatetruecolor($width, $height);
    $black = imagecolorallocate($image, 0, 0, 0);
    $white = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $white);

    for($i = 0; $i < $maxLines; $i++) {
        $line = (strlen($lines[$i]) > $maxCharsPerLine) ? substr($lines[$i], 0, $maxCharsPerLine) : $lines[$i];
        $line = ereg_replace("\t", "  ", $line);
        $line = ereg_replace("\r", "", $line);
         
        imagestring($image, $font, 3, ($i * $lineHeight), $line, $black);
    }

    imageline($image, 0, 0, $width, 0, $black);
    imageline($image, ($width - 1), 0, ($width - 1), ($height - 1), $black);
    imageline($image, ($width - 1), ($height - 1), 0, ($height - 1), $black);
    imageline($image, 0, ($height - 1), 0, 0, $black);    

    imagepng($image, $save_path);
    imagedestroy($image);
}


Wednesday, February 27, 2008

Create the progress bar in Javascript

http://www.dynamicdrive.com/dynamicindex11/dhtmlprogress.htm

HTML DOC TYPE

HTML DOC type doing the some major role in JS.
so check the DOC type if u found some strange browser compatibility issue.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




Javascript amazing

http://www.adrian.zentner.name/content/sitemap/index.html

Get the Height of the DIV in javascript

This will set the height of your div to the height of the browser window:
NOTE: 'divID' is the id name of the div in the html document.


window.onload = setDiv;

function setDiv() {
var wh = getWindowHeight(); // Window Height
var d = document.getElementById('divID') // Get div element
var dh = d.offsetHeight // div height
d.style.height = wh + 'px'; // Set div height to window height
}




function getWindowHeight() {
var windowHeight = 0;

if (typeof(window.innerHeight) == 'number')
windowHeight = window.innerHeight;

else {

if (document.documentElement && document.documentElement.clientHeight)
windowHeight = document.documentElement.clientHeight;

else {
if (document.body && document.body.clientHeight)
windowHeight = document.body.clientHeight; }; };

return windowHeight;
};

Perl With WinWord

http://www.adp-gmbh.ch/perl/word.html

Friday, February 22, 2008

Perl Exampl

#!"C:\xampp\perl\bin\perl.exe"
##
##  printenv -- demo CGI program which just prints its environment
##
print "Content-type: text/plain; charset=iso-8859-1\n\n";
print "sasi";

=cut
use mechanize;
my $ie = Mechanize->new( visible =>0 );
$ie->get('http://www.yahoo.com');
$content=$ie->content;
print $content;


   

print "Content-type: text/plain; charset=iso-8859-1\n\n";

print $request = $ENV{'QUERY_STRING'};


if ($ENV{'REQUEST_METHOD'} eq "GET") {

    $request = $ENV{'QUERY_STRING'};

} elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN, $request,$ENV{'CONTENT_LENGTH'})
        || die "Could not get query\n";

}


foreach $var (sort(keys(%ENV))) {
    $val = $ENV{$var};
    $val =~ s|\n|\\n|g;
    $val =~ s|"|\\"|g;
    print "${var}=\"${val}\"\n";
}
=end

Php ceil function to Round fractions up


<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

it will help for drop down pagination.

Thursday, February 21, 2008

email



--
Thankyou
with regards
Shanmugarajan.k
http://shanmugarajan.blogspot.com/
http://letus-know.blogspot.com/

pdf download on php

//$output = ob_get_flush(); //flushing the output
    ob_start(); //Turn on output buffering
    //This 5 lines codes are required to get pdf download in IE browser.
    header('Pragma: public');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: pre-check=0, post-check=0, max-age=0');
    header('Content-Transfer-Encoding: none');
    header('Content-type: application/pdf');
    header("Content-Disposition: attachment; filename=$pdf_name");
    readfile($filename);
    ob_flush();  //Flush (send) the output buffer

php xml parser with simplexml on attibutes

<?php
//$str = file_get_contents("app.xml")
$xml = simplexml_load_file("app.xml");

$cnt = count($xml->state);
$res = mysql_connect("localhost",'root', '') or die(mysql_error());

mysql_select_db("yourdb") or die(mysql_error());
for($i=0;$i<=$cnt;$i++){
    $countryName =mysql_escape_string($xml->state[$i]->name);
    foreach($xml->state[$i]->attributes() as $a => $b)
      {
      //echo $a,'="',$b,"\"</br>";
      //echo $b."<br>";
      $countryId=$b;
      }
echo "<br>".$sql ="INSERT INTO `yourtable` ( `country` , `country_short` ) VALUES ('$countryName', '$countryId' );";
      
      mysql_query($sql) or die(mysql_error);
}
?>

Wednesday, February 20, 2008

Image Icons

for sample image icons download.. please check on
http://www.icozon.com/index.php?mod=preview&id=107


Tuesday, February 19, 2008

World Map Links

To View & Save the wold map:

http://www.lib.utexas.edu/maps/world_maps/world_rel_803005AI_2003.jpg
http://web.mit.edu/kenta/www/one/world-map.png

php delete All files

<?
$source="foloder/*";
echo $rmcmd=" rm -r ".$source."";
    exec($rmcmd);
?>

Linux Commands

http://www.westwind.com/reference/OS-X/commandline/files-folders.html

Map view Display on your site

Hi
 Here we can found the map view easy integration stuff for your website.

 http://www.backspace.com/mapapp/


Monday, February 18, 2008

window.opener

window.opener.location.href ="url";

Thursday, February 14, 2008

Email validation in JavaScript

Email validation in javascript

function checkEmail(mailstring)
{
var parsed = true;
var filter =/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
if (!filter.test(mailstring))
{
parsed=false;
}
return parsed;
}

My Charactersketch





Charactersketch

The native will be ever pondering and slow in action thus usually missing many opportunities. His emotions will wax and wane. They will be sensitive and sympathetic. Anger may come and go in quick alternation. He will be fond of home and will be attached much to the family. He will be a home lover. The native may easily be influenced, thus he may have a changing attitude. But on certain issues he may be stubborn. the native will be fond of traveling and change.
He will be very honest about money matters. He will also have a secret strong desire to be very rich.

Regarding occupational matters the native will have lofty ambitions and great plans. He will think big and will prefer to have a circle of such friends. Native will believe in making connections through socializing. Native may have a natural flair and understanding for large business. Native will prefer a very professional work culture and will strive for growth and more growth.

Considering the negative side the native may become obstinate to a fault, and may not listen to other's point of view. He may work towards his goal very slowly missing many opportunities. Glutton tendencies may surface up. He may become very short tempered.
The native may choose his partner after a great deal of thinking. He will be a loyal and devoted husband. He will attend to the needs of the family. He will be fond of his partner and children. Will be a dutiful husband.

Cursor in MYSQL

Cursor in MYSQL


Cursor :

 
1 You need to declare a cursor for t1 table to go through its each and every record.
2 Open the cursor I have no idea about your tables in detail, if you have only one record in t2 table on base of t1 table, you can write a select statement to get that record or to check whether it is exists or not in t2 table but if you have multiple record then you need to write another cursor for t2 table to fetch each record and to get each an every record, and check whether record exist or not,if exist take another record from t1 else insert the t1 record into t2.
4 close cursor.
To use cursor in procedure there are four steps, declare, open,fetch and close.

example :

  CREATE PROCEDURE procedure1(empno INTEGER)               /* name */
           
 BEGIN                                      /* start of block */
 
  DECLARE cur CURSOR FOR
   // Use any one query from below
    SELECT empid FROM employee WHERE empid=empno;
     SELECT empid FROM employee WHERE ;
  open curl;
     emp_loop:LOOP
       FETCH curl INTO employeeId;
     END LOOP emp_loop;
  CLOSE cur;
 END                                       /* end of block */


In PHP File:
 
$link = mysqli_connect('localhost','root', '', 'DATASERVICE_SAMPLE');

 $result = mysqli_query($link,"CALL procedure1('1002')");

Wednesday, February 13, 2008

How to create Mysql Stored Procedure

Step-1
---------

Create Procedure First

Example
----------

USE DATASERVICE_SAMPLE ;
DROP PROCEDURE If EXISTS getEmployee ;
CREATE PROCEDURE getEmployee(empNo INTEGER) SELECT employeeNumber,lastName,firstName,email FROM Employees where employeeNumber = empNo ;
USE DATASERVICE_SAMPLE ;
DROP PROCEDURE If EXISTS getEmployee2 ;
CREATE PROCEDURE getEmployee2(empNo INTEGER) SELECT employeeNumber,lastName,firstName,email FROM Employees where employeeNumber = empNo ;

Step 1 : save above as the file in some path: $path(test.sql)

Step 2 : go to command prompt  mysql -u root -p 

Step 3 : run -> source $path  (ex: source test.sql)



IN PHP FILE:


   $link = mysqli_connect('localhost','root', '', 'DATASERVICE_SAMPLE');

  $result = mysqli_query($link,"CALL getEmployee('1002')");
  if( $result ){
      while( $row = mysqli_fetch_array($result) ){
        print_r($row );
      }
   }


 




Tuesday, February 12, 2008

Improve page load time in PHP

Improve page load time with a class and 3 lines of PHP


Here's a PHP script from Leon Chevalier which improves your page load time drastically. His compressor class improves your site's performance by combining and minifying the css, Javascript and HTML files on the page, allowing for fewer HTTP requests and smaller sizes of these files. All you need to do is to download the class file and add the following php lines at the top of your page

require_once('class.compressor.php');
$compressor = new compressor('css,javascript,page');

and the following line of PHP code at the end of your page

$compressor->finish();

Read more about this script and see the benchmarks of this over at: Aciddrop.com| Improve website load time by 500% with 3 lines of code

Thursday, February 7, 2008

Reduce the size of the html file using php gzip handler

If we apply gzip on our any huge html page it'll improve the performance?

Just add the following line after your sessions

<?php

ob_start
("ob_gzhandler");

?>

Wednesday, February 6, 2008

Javascript With PHP Array Examples

<?php 
$n = array('test','test2');
echo '<script type="text/javascript">';
echo 'var n = new array("', join($n,'","'), '");';
echo '</script>';
?>



<script type="text/javascript">
var buffer = "";
for(var i in n){
buffer += "n[" + i + "]= " + n[i] + "\n";
}
alert(buffer);
</script>

Php with Javascript Array

<?php $array = array('one''two''three'); ?>

<script language="JavaScript" type="text/JavaScript">

var xx=new Array("<?=implode("\",\""$array); ?>")

</script>

http://www.magmypic.com/

http://www.magmypic.com/

Tuesday, February 5, 2008

Iframe Attributes

Iframe Attributes:


  • SRC: URL of the document to go in the frame
  • HEIGHT: height of the inline frame
  • WIDTH: width of the inline frame
  • NAME: name of this inline frame
  • LONGDESC: URL of a long description of the contents of the frame
  • FRAMEBORDER: if the frame should have a border around it
 
  • MARGINWIDTH: internal left/right margin for the frame
  • MARGINHEIGHT: internal top/bottom margin for the frame
  • SCROLLING: if the frame should have scroll bars
  • ALIGN: alignment of the frame object to text around it
  • VSPACE: space above and below the frame
  • HSPACE: space to the left and right of the frame