Facebook

Friday, June 29, 2012

MySql Backup Class



MySql Backup Class  written by Vagharshak Tozalakyan <vagh@armdex.com>

This class is written in a file mysql_backup.class.php
This file is to be included in the file where we actually call this class to be executed.




HOW TO USE


HOW TO USE

1. Create the instance of MySQL_Backup class.
2. Define necessary properties.
3. Call Execute() method to create backup.

require_once 'mysql_backup.class.php';
$backup_obj = new MySQL_Backup();
$backup_obj->server = 'localhost';
$backup_obj->username = 'username';
$backup_obj->password = 'password';
$backup_obj->database = 'dbname';
$backup_obj->tables = array();
$backup_obj->drop_tables = true;
$backup_obj->struct_only = false;
$backup_obj->comments = true;
$backup_obj->fname_format = 'd_m_y__H_i_s';
if (!$backup_obj->Execute(MSB_DOWNLOAD, '', true))
{
  die($backup_obj->error);
}



PUBLIC PROPERTIES

var $server = 'localhost';
The name of MySQL server.

var $port = 3306;
The port of MySQl server.

var $username = 'root';
Database username.

var $password = '';
Database password.

var $database = '';
Name of the database.

var $link_id = -1;
MySQL link identifier of the current connection. You can set this if you
want to connect the MySQL server by your own.

var $connected = false;
Set true if the connection is already established before calling Execute().

var $tables = array();
Tables you want to backup. All tables in the database will be backed up if
this array is empty.

var $drop_tables = true;
Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.

var $struct_only = false;
Only structure of the tables will be backed up if true.

var $comments = true;
Include comments in backup file if true.

var $backup_dir = '';
Directory on the server where the backup file will be placed. Used only if task
parameter equals to MSB_SAVE in Execute() method.

var $fname_format = 'd_m_y__H_i_s';
Default file name format.

var $error = '';
Error message.


PUBLIC METHODS

function Execute($task = MSB_STRING, $fname = '', $compress = false)
$task - operation to perform: MSB_STRING - return SQL commands as a string;
  MSB_SAVE - create the backup file on the server; MSB_DOWNLOAD - save backup
  file in the user's computer.
$fname - optional name of backup file.
$compress - use GZip compression?




mysql_backup.class.php
<?php

/*
  MySQL database backup class, version 1.0.0
  Written by Vagharshak Tozalakyan <vagh@armdex.com>
  Released under GNU Public license
*/


define('MSB_VERSION', '1.0.0');

define('MSB_NL', "\r\n");

define('MSB_STRING', 0);
define('MSB_DOWNLOAD', 1);
define('MSB_SAVE', 2);

class MySQL_Backup
{

  var $server = 'localhost';
  var $port = 3306;
  var $username = 'root';
  var $password = '';
  var $database = '';
  var $link_id = -1;
  var $connected = false;
  var $tables = array();
  var $drop_tables = true;
  var $struct_only = false;
  var $comments = true;
  var $backup_dir = '';
  var $fname_format = 'd_m_y__H_i_s';
  var $error = '';


  function Execute($task = MSB_STRING, $fname = '', $compress = false)
  {
    if (!($sql = $this->_Retrieve()))
    {
      return false;
    }
    if ($task == MSB_SAVE)
    {
      if (empty($fname))
      {
        $fname = $this->backup_dir;
        $fname .= date($this->fname_format);
        $fname .= ($compress ? '.sql.gz' : '.sql');
      }
      return $this->_SaveToFile($fname, $sql, $compress);
    }
    elseif ($task == MSB_DOWNLOAD)
    {
      if (empty($fname))
      {
        $fname = date($this->fname_format);
        $fname .= ($compress ? '.sql.gz' : '.sql');
      }
      return $this->_DownloadFile($fname, $sql, $compress);
    }
    else
    {
      return $sql;
    }
  }


  function _Connect()
  {
    $value = false;
    if (!$this->connected)
    {
      $host = $this->server . ':' . $this->port;
      $this->link_id = mysql_connect($host, $this->username, $this->password);
    }
    if ($this->link_id)
    {
      if (empty($this->database))
      {
        $value = true;
      }
      elseif ($this->link_id !== -1)
      {
        $value = mysql_select_db($this->database, $this->link_id);
      }
      else
      {
        $value = mysql_select_db($this->database);
      }
    }
    if (!$value)
    {
      $this->error = mysql_error();
    }
    return $value;
  }


  function _Query($sql)
  {
    if ($this->link_id !== -1)
    {
      $result = mysql_query($sql, $this->link_id);
    }
    else
    {
      $result = mysql_query($sql);
    }
    if (!$result)
    {
      $this->error = mysql_error();
    }
    return $result;
  }


  function _GetTables()
  {
    $value = array();
    if (!($result = $this->_Query('SHOW TABLES')))
    {
      return false;
    }
    while ($row = mysql_fetch_row($result))
    {
      if (empty($this->tables) || in_array($row[0], $this->tables))
      {
        $value[] = $row[0];
      }
    }
    if (!sizeof($value))
    {
      $this->error = 'No tables found in database.';
      return false;
    }
    return $value;
  }


  function _DumpTable($table)
  {
    $value = '';
    $this->_Query('LOCK TABLES ' . $table . ' WRITE');
    if ($this->comments)
    {
      $value .= '#' . MSB_NL;
      $value .= '# Table structure for table `' . $table . '`' . MSB_NL;
      $value .= '#' . MSB_NL . MSB_NL;
    }
    if ($this->drop_tables)
    {
      $value .= 'DROP TABLE IF EXISTS `' . $table . '`;' . MSB_NL;
    }
    if (!($result = $this->_Query('SHOW CREATE TABLE ' . $table)))
    {
      return false;
    }
    $row = mysql_fetch_assoc($result);
    $value .= str_replace("\n", MSB_NL, $row['Create Table']) . ';';
    $value .= MSB_NL . MSB_NL;
    if (!$this->struct_only)
    {
      if ($this->comments)
      {
        $value .= '#' . MSB_NL;
        $value .= '# Dumping data for table `' . $table . '`' . MSB_NL;
        $value .= '#' . MSB_NL . MSB_NL;
      }
      $value .= $this->_GetInserts($table);
    }
    $value .= MSB_NL . MSB_NL;
    $this->_Query('UNLOCK TABLES');
    return $value;
  }


  function _GetInserts($table)
  {
    $value = '';
    if (!($result = $this->_Query('SELECT * FROM ' . $table)))
    {
      return false;
    }
    while ($row = mysql_fetch_row($result))
    {
      $values = '';
      foreach ($row as $data)
      {
        $values .= '\'' . addslashes($data) . '\', ';
      }
      $values = substr($values, 0, -2);
      $value .= 'INSERT INTO ' . $table . ' VALUES (' . $values . ');' . MSB_NL;
    }
    return $value;
  }


  function _Retrieve()
  {
    $value = '';
    if (!$this->_Connect())
    {
      return false;
    }
    if ($this->comments)
    {
      $value .= '#' . MSB_NL;
      $value .= '# MySQL database dump' . MSB_NL;
      $value .= '# Created by MySQL_Backup class, ver. ' . MSB_VERSION . MSB_NL;
      $value .= '#' . MSB_NL;
      $value .= '# Host: ' . $this->server . MSB_NL;
      $value .= '# Generated: ' . date('M j, Y') . ' at ' . date('H:i') . MSB_NL;
      $value .= '# MySQL version: ' . mysql_get_server_info() . MSB_NL;
      $value .= '# PHP version: ' . phpversion() . MSB_NL;
      if (!empty($this->database))
      {
        $value .= '#' . MSB_NL;
        $value .= '# Database: `' . $this->database . '`' . MSB_NL;
      }
      $value .= '#' . MSB_NL . MSB_NL . MSB_NL;
    }
    if (!($tables = $this->_GetTables()))
    {
      return false;
    }
    foreach ($tables as $table)
    {
      if (!($table_dump = $this->_DumpTable($table)))
      {
        $this->error = mysql_error();
        return false;
      }
      $value .= $table_dump;
    }
    return $value;
  }


  function _SaveToFile($fname, $sql, $compress)
  {
    if ($compress)
    {
      if (!($zf = gzopen($fname, 'w9')))
      {
        $this->error = 'Can\'t create the output file.';
        return false;
      }
      gzwrite($zf, $sql);
      gzclose($zf);
    }
    else
    {
      if (!($f = fopen($fname, 'w')))
      {
        $this->error = 'Can\'t create the output file.';
        return false;
      }
      fwrite($f, $sql);
      fclose($f);
    }
    return true;
  }


  function _DownloadFile($fname, $sql, $compress)
  {
    header('Content-disposition: filename=' . $fname);
    header('Content-type: application/octetstream');
    header('Pragma: no-cache');
    header('Expires: 0');
    echo ($compress ? gzencode($sql) : $sql);
    return true;
  }

}

?>




execute_db_backup.php

<?
/*
|-----------------------
|Example MySQL Backup File  
|  
|Written by: Justin Keller <kobenews@cox.net>
|Released under GNU Public license.
|
|Only use with MySQL database backup class,
|version 1.0.0 written by Vagharshak Tozalakyan
|<vagh@armdex.com>.
|-----------------------
*/

require_once 'mysql_backup.class.php';
$backup_obj = new MySQL_Backup();

//--- EDIT - REQUIRED SETUP VARIABLES ------->>

$backup_obj->server = 'localhost';
$backup_obj->port = 3306;
$backup_obj->username = '';
$backup_obj->password = '';
$backup_obj->database = '';

//Tables you wish to backup. All tables in the database will be backed up if this array is null.
$backup_obj->tables = array();

//--- END - REQUIRED SETUP VARIABLES  ------->>

//---OPTIONAL PREFERENCE VARIABLES ------->>

//Add DROP TABLE IF EXISTS queries before CREATE TABLE in backup file.
$backup_obj->drop_tables = true;

//Only structure of the tables will be backed up if true.
$backup_obj->struct_only = false;

//Include comments in backup file if true.
$backup_obj->comments = true;

//Directory on the server where the backup file will be placed. Used only if task parameter equals MSB_SAVE.
$backup_obj->backup_dir = '/';

//Default file name format.
$backup_obj->fname_format = 'm_d_Y';

//---END - OPTIONAL PREFERENCE VARIABLES ------->>

//---EDIT - REQUIRED EXECUTE VARIABLES ------->>

/*
Task:
MSB_STRING - Return SQL commands as a single output string.
MSB_SAVE - Create the backup file on the server.
MSB_DOWNLOAD - Download backup file to the user's computer.

*/
$task = MSB_DOWNLOAD;

//Optional name of backup file if using 'MSB_SAVE' or 'MSB_DOWNLOAD'. If nothing is passed, the default file name format will be used.
$filename = '';

//Use GZip compression if using 'MSB_SAVE' or 'MSB_DOWNLOAD'?
$use_gzip = true;

//---END - REQUIRED EXECUTE VARIABLES ------->>

//---NO NEED TO ANYTHING BELOW THIS LINE ------->>

if (!$backup_obj->Execute($task, $filename, $use_gzip))
{
$output = $backup_obj->error;
}
else
{
$output = 'Operation Completed Successfully At: <b>' . date('g:i:s A') . '</b><i> ( Local Server Time )</i>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>MySQL Backup</title>
</head>
<body>
<?
echo $output;
?>
</body>
</html>

Saturday, February 4, 2012

Looping through XML with jQuery

Handling Xml on web pages is used to be a headache when i started coding ajax events. Most of the times we will be knowing the tag name of particular data we need and we can use
xml.find('result').find('userTypeDetails')

 But this is not always the case with xml.
I have a scenario in which i get an xml like the one follows as ajax response.

<result>
    <permissionDetails>
             <addBusiness>0</addBusiness>
             <viewBusiness>1</viewBusiness>
             <viewBusinessChargeDetails>1</viewBusinessChargeDetails>
             <editBusinessProfile>0</editBusinessProfile>
             <editBusinessAccount>1</editBusinessAccount>
             <editBusinessGatewayInfo>1</editBusinessGatewayInfo>
             <deleteBusiness>1</deleteBusiness>
             <addBillingUser>0</addBillingUser>
             <viewBillingUser>0</viewBillingUser>
             <viewBillingUserChargeDetails>0</viewBillingUserChargeDetails>
             <editBillingUserProfile>1</editBillingUserProfile>
             <editBillingUserAccount>1</editBillingUserAccount>
             <deleteBillingUser>1</deleteBillingUser>
             <viewCharge>0</viewCharge>
             <editCharge>1</editCharge>
             <viewRegularReport>0</viewRegularReport>
             <addRegularReport>0</addRegularReport>
             <editRegularReport>0</editRegularReport>
             <deleteRegularReport>0</deleteRegularReport>
             <viewAdvancedReport>1</viewAdvancedReport>
             <addAdvancedReport>0</addAdvancedReport>
             <editAdvancedReport>1</editAdvancedReport>
             <deleteAdvancedReport>1</deleteAdvancedReport>
             <viewUser>0</viewUser>
             <addUser>0</addUser>
             <editUser>1</editUser>
             <deleteUser>1</deleteUser>
             <viewTemplate>0</viewTemplate>
             <addTemplate>0</addTemplate>
             <editTemplate>0</editTemplate>
             <deleteTemplate>1</deleteTemplate>
             <viewMail>1</viewMail>
             <sendMail>1</sendMail>
             <deleteMail>0</deleteMail>
             <profileDetailsView>1</profileDetailsView>
             <profileDetailsEdit>1</profileDetailsEdit>
             <viewAccount>0</viewAccount>
             <editAccount>1</editAccount>
             <deleteAccount>1</deleteAccount>
             <viewGatewayInfo>1</viewGatewayInfo>
             <editGatewayInfo>1</editGatewayInfo>
             <deleteGatewayInfo>0</deleteGatewayInfo>
    </permissionDetails>
</result>

Now i have to update an html page as in figure

One of the solution is to create checkboxes with name same as tagname in xml and iterate through the xml to check or uncheck the check box with name same as the current tag name depending upon value.
dd

xml.find('result').find('permissionDetails').each(function(){
    $(this).children().each(function(){
        var tagName=this.tagName;
        var val=$(this).text();
        if(val==1){
            $('input:checkbox[name='+tagName+']').attr('checked',true);
        }
        else if(val==0){
            $('input:checkbox[name='+tagName+']').removeAttr('checked');
        }
    })
});

Friday, February 3, 2012

code ignitor: Getting the error “Disallowed Key Characters”


Code Ignitor: Getting the error “Disallowed Key Characters” ?

   In Codeignitor, its usual for the developer getting the Error: "Disallowed Key Characters"
 This error used to drove newbies nuts. I am not sure about the reason and the fix provided by codeignitor help page not works some times[Most of the times from my experience]. It is also difficult to find what caused the error.

Here is solution that help in diagnosis of the problem.

In the core CI code in system/libraries is a file called input.php This small modification would show the actual data that caused the Problem.

Around line number 199


function _clean_input_keys($str)
{
if ( ! preg_match(“/^[a-z0-9:_\/-]+$/i”, $str))
{
exit(‘Disallowed Key Characters: ‘.$str);
// The variable $str was added to display the data in question.
}
return $str;
}

jQuery: exclude $(this) from selector


I have a set of text boxes and i want to check for duplication of set values in any of the text box. ie, no text box should contain a value that is entered in any other.

HTML
<form method="post" action="" onsubmit="return validate()">
   <table>
       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>
   </table>
</form>
DEMO

JAVASCRIPT


var firstError='';
function validate(){
     $('input[type="text"]').each(function(){
var mastrPriority=$(this);
$('input[type="text"]').not(this).each(function(){
var priority=$(this);
if(mastrPriority.val()==priority.val()){
  seterrormessage(mastrPriority,'Duplicate Priority Values.');
seterrormessage(priority,'Duplicate Priority Values.');
if(firstError==''){
alert("Priority Field should contain unique values.");
firstError=mastrPriority;
}
}
});

})
if(firstError!=''){
  firstError.focus();
return false;
}
else{
  return true;
}
}


function seterrormessage(field,msg){
var errorBox=$(field).parent().find('div.validationError').first();
if(errorBox.length>0){
  errorBox.text(msg);
}
else{
  $(field).after('</br><div class="validationError">'+msg+'</a>');
}
}
The function validate() iterates through each text box and compare values of each box with all others except current one. The current text box is excluded from the set of text boxes using .not(this).

Wednesday, January 4, 2012

Find your user's their IP address:


Show your user's their IP address:

Retrieving the user's IP address is actually much simpler than you might think, and can be done in a single line. Getenv("REMOTE_ADDR") will return the IP address of the person visiting your site. Generally this is accurate, however if the user is running through a proxie server, then it will return the address of the proxie.
In this example, we retrieve the user's IP and then simply echo it's value back to the user.
<?php
 //Gets the IP address
 $ip = getenv("REMOTE_ADDR") ;
 Echo "Your IP is " . $ip;
 ?>

Monday, December 5, 2011

How do I count the number of tr elements within a table using jquery.


This can be a most basic question, but it may keep us busy us for hours wasting our time.

Use a selector that will select all the rows and take the length.
var rowCount = $('#myTable tr').length;

Note: this approach also counts all trs of every nested table!
$('#myTable tr').size() will return the same value
the docs indicate that length is preferred over size() because it's faster

Sunday, December 4, 2011

Javascript IsInteger


A simple and javascript function to check whether the string is an integer.

function isInteger(s){
var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))){
return false;
}
    }
    // All characters are numbers.
    return true;
}

Saturday, December 3, 2011

How to change PHP's eregi to preg_match



This function eregi has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Now what we need is to replace the eregi functions used in our old applications with some new functions that are still not depreciated...
First i will describe functionality of eregi() and then i will go for appropriate function to replace it.

eregi():
eregi — Case insensitive regular expression match
Syntax:

int eregi ( string $pattern , string $string [, array &$regs ] )

This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters.


Parameters






pattern
Case insensitive regular expression.
string
The input string.
regs
If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.
$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.


return Values

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.
If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

A good alternative is to use preg_match() function

Now lets talk about preg_match

preg_match — Perform a regular expression match

Description

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int$offset = 0 ]]] )
Searches subject for a match to the regular expression given in pattern.

More details can be found at php.net http://in2.php.net/manual/en/function.preg-match.php

Now How to replace eregi with preg_match


You will need to change three things
  1. need to add pattern delimiters (can be any character, but most commonly a forward slash)
  2. [[:alnum:]] will need to be replaced with the PCRE equivalent
  3. The "i" in "eregi" means case-insensitive, which PCRE does with a flag, specifically the i flag.
Otherwise, the rest looks PCRE compatible (yes, that's kind of redundant =P)
"/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i"


Thursday, December 1, 2011

How to change version of php in Xampp


Take this example that makes PHP version from 5.3 to 5.2 in Xampp


  1. Download and install latest xampp to G:\xampp. As of 2010/03/12, this is 1.7.3.
  2. Download the zip of xampp-win32-1.7.0.zip, which is the latest xampp distro without php 5.3. Extract somewhere, e.g. G:\xampp-win32-1.7.0\
  3. Remove directory G:\xampp\php
  4. Remove G:\xampp\apache\modules\php5apache2_2.dll and php5apache2_2_filter.dll
  5. Copy G:\xampp-win32-1.7.0\xampp\php to G:\xampp\php.
  6. Copy G:\xampp-win32-1.7.0\xampp\apache\bin\php* to G:\xampp\apache\bin
  7. Edit G:\xampp\apache\conf\extra\httpd-xampp.conf.
    • Immediately after the line, <IfModule alias_module> add the lines
(snip)
<IfModule mime_module>
  LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"
  AddType application/x-httpd-php-source .phps
  AddType application/x-httpd-php .php .php5 .php4 .php3 .phtml .phpt
    <Directory "/xampp/htdocs/xampp">
      <IfModule php5_module>
        <Files "status.php">
            php_admin_flag safe_mode off
        </Files>
      </IfModule>
    </Directory>
</IfModule>
(Note that this is taken from the same file in the 1.7.0 xampp distribution. If you run into trouble, check that conf file and make the new one match it.)
You should then be able to start the apache server with PHP 5.2.8. You can tail the G:\xampp\apache\logs\error.log file to see whether there are any errors on startup. If not, you should be able to see the XAMPP splash screen when you navigate to localhost.