Monday 18 October 2010

How to Find and Replace Text in MySQL Database?

Use the following syntax for replacing text in mysql:

The syntax of REPLACE is REPLACE(text_string, from_string, to_string)

SELECT REPLACE(‘www.mysql.com’, ‘my’, ‘you');

and result will be:

www.yousql.com

Cheers!

Friday 8 October 2010

How to remove hyperlink from a string using php?

<?php

function findAndReplace($arr) {
    return '<strong>'.$arr[1].'</strong>';
}

$inputText = 'Why use <a href="#"  style="padding-left:5px"> PHP </a>?';
echo "<br />Input is: <br />";
echo $inputText;

$returnText = preg_replace_callback('@<a(?:.*)>(.*)</a>@isU', 'findAndReplace', $inputText);

echo "<br /><br />Output will be: <br />";
echo $returnText;

?>

Input is:
Why use PHP ?

Output will be:
Why use PHP ?

Wednesday 29 September 2010

How to create Custom Error Messages in Apache?

Below is the way to create custom error message using Apache:

Below is an example of a .htaccess file, just copy and paste into your file, but change the paths:
ErrorDocument 404 /path_to_your_error_file_or_script
ErrorDocument 403 /path_to_your_error_file_or_script 
ErrorDocument 500 /path_to_your_error_file_or_script

Examples:
Full path would be http://www.yourwebsite.com/path_to_your_error_file_or_script
Absolute path would be /home/yoursite.com/path_to_your_error_file_or_script
Relative path would be /path_to_your_error_file_or_script
To summarise the steps, they are as follows:
  1. Create a text file, and add to it a line for each error and rename it .htaccess
  2. Upload the files/script that the .htaccess file calls in each error.
  3. TEST! By typing a weird URL in the address box - you should get the 404 custom error.
Now you are done!

Cheers!

How to store UTF8 (indian language) data in mysql?

We assume we have a DataBase with table news, and a column named posts, which will save the news written in your website.We know that all major DataBase’s support UTF8. And we shall explore that feature.
Now we write a article in hindi, हेल्लो वर्ल्ड
If the UTF8 is not specified, you should see something like ?????? in ur DataBase otherwise you should see the hindi data. Clear? Now lets see the code given below:


First check for UTF8 compatibility with this query. If it supports you should see the output as “Character_set_system”| “UTF8″
SHOW VARIABLES LIKE ‘character_set_system’;
this will show the below result if support:
Full Texts
Variable_name    Value
character_set_system    utf8


Now that being checked, alter the table and just modify the column, which is 'text' in our above example and specify it as UTF8
ALTER TABLE news MODIFY text VARCHAR(200) CHARACTER SET UTF8;

Then execute following query before inserting into the table:

mysql_query('SET character_set_results=utf8');       
mysql_query('SET names=utf8');       
mysql_query('SET character_set_client=utf8');       
mysql_query('SET character_set_connection=utf8');
mysql_query('SET collation_connection=utf8_general_ci');


 
Now, try to insert the hindi value and save it. Query it and u should see the hindi text :)


 Cheers!

Wednesday 11 August 2010

How to make database IP live using ubuntu?

$ vi /etc/mysql/my.cnf

search bind_address..
comment bind_address..

$ sudo -s -H

$ ls -l /etc | grep my

$ ls -l /etc/mysql | grep my

$ /etc/init.d/mysql restart

$ mysql -u root -p

mysql > show grants;

Now you will see the following query:
 GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' WITH GRANT OPTION
Copy above query and paste it into terminal and replace 'localhost' by %.

mysql > flush privileges;

Cheers!

Monday 19 July 2010

How to unzip tar.gz file in ubuntu?

Hi guys,

Please use the following command:

tar xvzf something.tar.gz

Cheers!

Sunday 18 July 2010

The 8 ball problem?

Hie All,

Please use the following and get the result in 2 iteration:

You can identify the heavier ball in only 2 weighings! 

The secret is not to get fooled into the "divide and conquer" approach where the input is halved in each iteration as explained above.
To achieve this in only 2 weighings, you first put 3 balls in each bowl on the scale, e.g. {1,2,3} against {4,5,6}.
Should the scale balance, you have only 2 balls remaining which you can compare by putting each in a separate bowl on the scale, e.g. {7} against {8}.
Should the scale not balance, however, take the 3 balls from the heavier bowl on the scale (e.g. 1,2,3).
Pick any 2 balls and compare these against each other, e.g. {1} against {2}. If the scale balances, you know it is ball 3 is the heavier. Is the scale moving, you know it's the ball on the heavier side. 


Thanks & Cheers!

Tuesday 6 July 2010

How to get connection from doctrine to run sql query in Symfony?

Hey folks,

$db = Doctrine_Manager::getInstance()->getCurrentConnection();
$sql = "UPDATE admin_info SET admin_category='".$permissions."' WHERE username = '".$username."'";
$result = $db->execute($sql);       
return $result;

Cheers!

Tuesday 29 June 2010

How to Install MEMCACHED on ubuntu?

first of all write the following command on command line:

sudo apt-get install memcached
now go to php.ini file and enable memcache.so


OR

following command automatically append php.ini file and write memcache.so

sudo apt-get install php5-memcache memcached


now check memcached is running or not?

type

/etc/init.d/memcached status

/etc/init.d/memcached start

To check wether 11211 port is enable or not with 127.0.0.1
telnet 127.0.01 11211

Now run the memcached script on server:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
<?php

        // put your code here
        $cache = new Memcache();

        $cache->connect("127.0.0.1");
        //addServer("127.0.0.1",11211);
        $user_key = 12345;

    /** Look in cache, if not found, set object (misses null) **/
    if (!$user = $cache->get($user_key)) {
      /**
       * Set object with expire of 1 hour and no compression
       */
      $value = array(34,56,34,23,23,124,65,767,34,76576,99);
      $cache->set($user_key, $value, NULL, 6000);
      $user = $value;
      echo "In";
    }
    else
    {
            $tVar = $cache->get($user_key);
        echo '<PRE>';
        print_r($tVar);
        echo "Out";
    }
        ?>
    </body>
</html>


This script will first time enter in if condition and second time in else condition.... if it does then your memcached is working fine else there is some error.

Cheers!

Friday 25 June 2010

How to login on other server using command line?

Write down the following in the terminal:

$ ssh <username>@<IP Address>
and then press enter. It will be asked to enter password.
give password and you are done.

e.g.,

$ ssh root@10.10.12.40
it will ask password. give password and done.

Cheers!

what are 777 means in sense of permissions?

Whenever we give permission to the folder or anything, we usually write 777.
Here are three 777.
First seven means permission is giving to User(Owner)
Second seven means permission is giving to Group
Third seven means permission is giving to Others

so 777 means UGO

now comes to each 7. what the means of 7?

each 7 consist read, write or execute permission.

therefore,

read(r)      : 4
write(w)     : 2
execute(x) : 1


Suppose, if we want to give read, write and execute permission then

read + write + execute (rwx) => 4 +2 + 1 => 7
read + write (rw) => 4 + 2 => 6
read + execute (rx) => 4 + 1 => 5
write + execute (wx) => 2+1 => 3

Cheers!

What are the http/1.1 status code?

   '100' => 'Continue',
    '101' => 'Switching Protocols',
    '200' => 'OK',
    '201' => 'Created',
    '202' => 'Accepted',
    '203' => 'Non-Authoritative Information',
    '204' => 'No Content',
    '205' => 'Reset Content',
    '206' => 'Partial Content',
    '300' => 'Multiple Choices',
    '301' => 'Moved Permanently',
    '302' => 'Found',
    '303' => 'See Other',
    '304' => 'Not Modified',
    '305' => 'Use Proxy',
    '306' => '(Unused)',
    '307' => 'Temporary Redirect',
    '400' => 'Bad Request',
    '401' => 'Unauthorized',
    '402' => 'Payment Required',
    '403' => 'Forbidden',
    '404' => 'Not Found',
    '405' => 'Method Not Allowed',
    '406' => 'Not Acceptable',
    '407' => 'Proxy Authentication Required',
    '408' => 'Request Timeout',
    '409' => 'Conflict',
    '410' => 'Gone',
    '411' => 'Length Required',
    '412' => 'Precondition Failed',
    '413' => 'Request Entity Too Large',
    '414' => 'Request-URI Too Long',
    '415' => 'Unsupported Media Type',
    '416' => 'Requested Range Not Satisfiable',
    '417' => 'Expectation Failed',
    '500' => 'Internal Server Error',
    '501' => 'Not Implemented',
    '502' => 'Bad Gateway',
    '503' => 'Service Unavailable',
    '504' => 'Gateway Timeout',
    '505' => 'HTTP Version Not Supported',

Cheers!

How to check session is exit or not using ajax call with jquery?

Hey fox please do the below mentioned code to check it out whether session is exist or not via ajax call:


Write down the following code while call ajax;

function callAjax()
    {
        $.ajax({       
               data: { fname: 'ashwani kumar' },             
              type: 'POST',
                  url: 'ajax.php',
                success: function(data) {
                    alert('success');
                    $('#content').html(data);           
                 },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                     //alert(XMLHttpRequest.status);
                    if (XMLHttpRequest.status === 500) {
                      location.href = 'index.php';
                    }
                  }
            });
    }

IN ajax.php file on top of the page write down the following code in your script:

if(!isset($_SESSION['name']))
{
    header("HTTP/1.0 500 Not Found");
    exit;
}


Cheers!

Monday 21 June 2010

How to post form using ajax in jquery?

 $.post(url, $("#"+$formname).serialize(),
    function(data){
      $('#content').html(data);
    });

Cheers!

Thursday 17 June 2010

How to download/checkout code from svn?

go to the directory where you wanna download code and then write the following in terminal:

$ svn co codepath ./

Cheers!

How to import sql file using linux?

First go to the directory where your sql file is saved and then type the following: 

$ mysql -u root -p payforme < payforme_dev.sql

Here  
root is the username of mysql
payforme is the database name
payforme_dev.sql is the sql file.

Cheers!

Tuesday 15 June 2010

How to start/stop/restart apache on ubuntu?

## start apache on ubuntu...
$ sudo /etc/init.d/apache2 start

## stop apache on ubuntu...
$ sudo /etc/init.d/apache2 stop

## restart apache on ubuntu...
$ sudo /etc/init.d/apache2 restart



Cheers!

How to install curl on ubuntu?

## install curl in php on ubuntu...

$ sudo apt-get install php5-curl

Friday 11 June 2010

How to create query parameter in symfony?

There are two ways to make query parameters:

First Method:


$params = array(
    'name'    => $request->getParameter('name'),
    'email'   => $request->getParameter('email'),
    'message' => $request->getParameter('message'),
  );

http_build_query($params);

Second Method:

$this->form = new ContactForm();
http_build_query($this->form->getValues());


Cheers!

Create Module from command line in symfony?

First go to the your project folder and then type 

$ php symfony generate:module frontend contact

it will generate all the folder related to contact module.

Cheers!

How to clear Simfony Chache?

First go to the project foleder and then type the following command on command line i.e., Terminal

$ php symfoy cc

and then press enter.

This will clear all the cache of your project.

Thanks

Cheers!

How to GET, POST or REQUEST parameters in symfony?

suppose, randomToken variable coming from the last page either GET or POST.

Using the following command, you can fetch that variable:

$rondomToken = $this->getRequestParameter('randomToken');

Cheers!

How to set Cookie in symfony?

// cookie getter
$string = $this->getRequest()->getCookie('mycookie');
 
// cookie setter
$this->getResponse()->setCookie('mycookie', $value);
 
// cookie setter with options
$this->getResponse()->setCookie('mycookie', $value, $expire, $path, $domain, $secure);
 
If you want to manipulate cookies outside of an action, you will need to access the Request and Answer objects without shortcut: 
 
$request  = sfContext::getInstance()->getRequest();
$response = sfContext::getInstance()->getResponse();
 
 
Cheers! 

How to set, get and remove session variables in symfony?

## Create Session Variables...
$this->getUser()->setAttribute('nickname', 'ashwani');


## Retrieve Session Variables...
$this->nickname = $this->getUser()->getAttribute('nickname');
   
## Check if session is exist return 1 else blank value...
$hasNickname = $this->getUser()->hasAttribute('nickname');

## Remove Session Variable...
$this->getUser()->getAttributeHolder()->remove('nickname');

Cheers!

Wednesday 9 June 2010

How to see IP Address of a system in Linux?

Write following command on command line:

$ /sbin/ifconfig/

As soon as you enter, you will se following on the screen:

eth0      Link encap:Ethernet  HWaddr 00:25:64:ba:67:2d 
          inet addr:192.168.29.231  Bcast:192.168.29.255  Mask:255.255.255.192
          inet6 addr: fe80::225:64ff:feba:672d/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:51598 errors:0 dropped:0 overruns:0 frame:0
          TX packets:27730 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:15121530 (14.4 MB)  TX bytes:6643763 (6.3 MB)
          Interrupt:16

lo        Link encap:Local Loopback 
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:12269 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12269 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:13829812 (13.1 MB)  TX bytes:13829812 (13.1 MB)

The bold text is your IP Address.

Thanks

Cheers!

What are the upload credentials for php.ini ?

Following are the hierarchy for uploading a file:

memory limit > upload post size > upload max filesize

by default in php.ini, it is 16M > 4M> 2M.

Cheers!

How to access LAMP configurations from putty?

Type the following command on command line:

For edit apache configuration file use the follwoing :
$ gedit /etc/apache2/httpd.conf
$ gedit /etc/apache2/apache2.conf


For edit php.ini file, use the follwoing :
$ gedit /etc/php5/apache2/php.ini

Cheers!

Friday 21 May 2010

What are the differences b/w GET and POST in ajax call?

var http = new XMLHttpRequest();

Using GET method

Now we open a connection using the GET method.

var url = "getdata.php";
var params = "name=ashwani&action=true";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
 if(http.readyState == 4 && http.status == 200) {
  alert(http.responseText);
 }
}
http.send(null);
I really hope that this much is clear for you - I am assuming that you know a bit of Ajax coding.



POST method

We are going to make some modifications so POST method will be used when sending the request...

var url = "getdata.php";
var params = "name=ashwani&action=true";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
 if(http.readyState == 4 && http.status == 200) {
  alert(http.responseText);
 }
}
http.send(params);

The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument - in the GET method, we send the parameters along with the url separated by a '?' character...

Cheers!

How many NULL values can Unique key contains?

An unique key can contains unlimited NULL values because each NULL value differ from another NULL value.

Cheers!

How to Speed Up Web Site?

There are the following steps through which you can speed up you web site:


  • Minimize HTTP Requests
  • Add an Expires or a Cache-Control Header
  • Gzip Components
  • Put Stylesheets at the Top
  • Put Scripts at the Bottom
  • Avoid CSS Expressions
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Avoid Redirects
  • Remove Duplicate Scripts
  • Make Ajax Cacheable
  • Flush the Buffer Early
  • Make favicon small and cacheable
  • Use GET for AJAX Requests

  • Reduce the Number of DOM Elements

     

           The number of DOM elements is easy to test, just type in Firebug's console:    

           document.getElementsByTagName('*').length 

Cheers!

Thursday 20 May 2010

What are Constructors and Destructors?

Constructor

void __construct ([ mixed $args [, $... ]] )
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. 

<?phpclass BaseClass {
   function 
__construct() {
       print 
"In BaseClass constructor\n";
   }
}

class 
SubClass extends BaseClass {
   function 
__construct() {
       
parent::__construct();
       print 
"In SubClass constructor\n";
   }
}
$obj = new BaseClass();$obj = new SubClass();?>
 
 

Destructor

void __destruct ( void )
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence. 


<?phpclass MyDestructableClass {
   function 
__construct() {
       print 
"In constructor\n";
       
$this->name "MyDestructableClass";
   }

   function 
__destruct() {
       print 
"Destroying " $this->name "\n";
   }
}
$obj = new MyDestructableClass();?>

 

What is static keyword?

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static). 

<?phpclass Foo{
    public static 
$my_static 'foo';

    public function 
staticValue() {
        return 
self::$my_static;
    }
}

class 
Bar extends Foo{
    public function 
fooStatic() {
        return 
parent::$my_static;
    }
}


print 
Foo::$my_static "\n";
$foo = new Foo();
print 
$foo->staticValue() . "\n";
print 
$foo->my_static "\n";      // Undefined "Property" my_static
print $foo::$my_static "\n";$classname 'Foo';
print 
$classname::$my_static "\n"// As of PHP 5.3.0
print Bar::$my_static "\n";$bar = new Bar();
print 
$bar->fooStatic() . "\n";?>

What is interface?

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface. 


<?php
// Declare the interface 'iTemplate'interface iTemplate{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}
// Implement the interface
// This will work
class Template implements iTemplate{
    private 
$vars = array();
 
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
 
    public function 
getHtml($template)
    {
        foreach(
$this->vars as $name => $value) {
            
$template str_replace('{' $name '}'$value$template);
        }

        return 
$template;
    }
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate{
    private 
$vars = array();
 
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
}
?>

What is abstract class?

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. 

<?phpabstract class AbstractClass{
    
// Force Extending class to define this method
    
abstract protected function getValue();
    abstract protected function 
prefixValue($prefix);

    
// Common method
    
public function printOut() {
        print 
$this->getValue() . "\n";
    }
}

class 
ConcreteClass1 extends AbstractClass{
    protected function 
getValue() {
        return 
"ConcreteClass1";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass1";
    }
}

class 
ConcreteClass2 extends AbstractClass{
    public function 
getValue() {
        return 
"ConcreteClass2";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass2";
    }
}
$class1 = new ConcreteClass1;$class1->printOut();
echo 
$class1->prefixValue('FOO_') ."\n";
$class2 = new ConcreteClass2;$class2->printOut();
echo 
$class2->prefixValue('FOO_') ."\n";?>

Monday 17 May 2010

How to create Singleton Class in PHP

<?php
class singleton
{
  
     /** Store the instance of the class */
     private static $instance;
    
     private function __construct()
     {
     }
    
     public static function getInstance()
     {
         //__CLASS__ is always resolved to this class, even if subclassed
         if (!self::$instance instanceof self)
         {
             self::$instance = new self();
         }
        
         return self::$instance;
     }
    
     public function __clone()
     {
        throw new Exception("Cloning of this object is not supported.");
     }
    
     public function someMethod()
     {
         echo "Doing something!";
     }

}
?>

Thursday 29 April 2010

What is node in drupal?

Basically it comes down to this: A node is a single piece of content that is published on a Drupal site.

Cheers!

Explain sort(), rsort(), asort(), arsort(), ksort(), krsort() and natsort()?

Suppose we have an array like below:

$fruits = array("lemon""orange""banana""apple");

1. sort()       
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
e.g.,
sort($fruits);

The above example will output:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange 


2. rsort()            
This function sorts an array in reverse order (highest to lowest).
Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
 e.g.,
rsort($fruits);


The above example will output:
0 = orange
1 = lemon
2 = banana
3 = apple


3. asort()              
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
e.g.,
asort($fruits);

The above example will output:
c = apple
b = banana
d = lemon
a = orange

4. arsort()               
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
e.g.,
arsort($fruits);

The above example will output:
a = orange
d = lemon
b = banana
c = apple
 
5. ksort()
               Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
e.g.,
ksort($fruits);

The above example will output:
a = orange
b = banana
c = apple
d = lemon

6. krsort()               
Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.
e.g.,
krsort($fruits);

The above example will output:
d = lemon
c = apple
b = banana
a = orange
 
7. natsort()
                 This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

e.g., 
<?php
$array1 
$array2 = array("img12.png""img10.png""img2.png""img1.png");
sort($array1);
echo 
"Standard sorting\n";print_r($array1);
natsort($array2);
echo 
"\nNatural order sorting\n";print_r($array2);?>  


The above example will output:
Standard sorting
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)



Cheers!





Explain the difference between mysql and mysqli?

mysqli is the improved version of mysql and it is mainly 
used for object oriented and stored procedure applications 
in php.
 
Cheers! 

Wednesday 21 April 2010

What is Drupal?

Drupal is software that allows an individual or a community of users to easily publish, manage and organize a great variety of content on a website.

Cheers!

How MySQL Uses Indexes?

Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows.
The larger the table, the more this costs.

If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

Cheers!

Describe UNION in mysql?

Union is used to merge records coming from different or same tables on different conditions.

for example:

SELECT id, name, age FROM employee WHERE id = 2
UNION
SELECT id, name, age FROM employee WHERE id = 5

Note:  both query contains same number of fields.


In above example, there are 3 fields in first query and 3 fields in second query.

Cheers!

How can session start without writing SESSION_START() on top of the page?

Yes, you can start session without writing SESSION_START() on top of the page.
Just go to the php.ini file and search session.auto_start.

You will see like this

session.auto_start = 0

write 1 instead of 0 and restart the server.

Cheers!

Tuesday 20 April 2010

What is TEMP TABLES in mysql?

The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be knows for temporary tables is that they will be deleted when the current client session terminates.


As stated earlier temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQl database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.


for example:

mysql> CREATE TEMPORARY TABLE employee(
    -> emp_name VARCHAR(50) NOT NULL
    -> , emp_age INT(11) NOT NULL DEFAULT 
-> , emp_class int(11) NOT NULL DEFAULT
);
 
Query OK, 0 rows affected (0.00 sec)
Cheers!

How to Preventing Duplicates from Occurring in a Table:

You can use INSERT IGNORE or REPLACE keyword to prevent duplicates  from occurring in a table.

Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an existing record, MySQL inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQL to discard it silently without generating an error.

for example:

mysql> INSERT IGNORE INTO employee_tbl (lastname, firstname)
    -> VALUES( 'Kumar', 'Ashwani');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT IGNORE INTO employee_tbl (lastname, firstname)
    -> VALUES( 'Kumar', 'Ashwani');
Query OK, 0 rows affected (0.00 sec)
INSERT IGNORE and REPLACE should be chosen according to the
duplicate-handling behavior you want to effect. INSERT IGNORE keeps the
first of a set of duplicated records and discards the rest. REPLACE
keeps the last of a set of duplicates and erase out any earlier ones.
 
 
Cheers!

Monday 19 April 2010

What are the components in Zend Framework?

The following are components zend including:
  • Zend_Acl (both Roles and Resources)
  • Zend_Auth provides an API for authentication
  • Zend_Cache provides a flexible approach toward caching data
  • Zend_Controller and Zend_View
  • Zend_Rest_Client and Zend_Rest_Server (Web Services)
  • Zend_XmlRpc
  • Zend_Feed, Zend_Filter and Zend_Validate
  • Zend_Gdata (Zend Google Data Client): Google Data APIs provide read/write access to such services hosted at google.com as Spreadsheets, Calendar, Blogger, and CodeSearch.
  • Zend_Json, Zend_Memory
  • Zend_Pdf (Can create or read PDF documents on the fly, without the need to call utilities from the shell. Zend_Pdf can modify existing PDF documents.)
  • Zend_Registry
  • Zend_Search_Lucene

Friday 16 April 2010

What is the difference between echo and print statement?

There is a slight difference between print and echo which would depend on how you want to use the outcome. Using the print method can return a true/false value.

This may be helpful during a script execution of somesort.
Echo does not return a value, but has been considered as a faster executed command.
All this can get into a rather complicated discussion, so for now, you can just use whichever one you prefer.

Cheers!

What is differenc between mysql_connect and mysql_pconnect?

mysql_pconnect establishes a persistent connection. If you don't need one (such as a website that is mostly HTML files or PHP files that don't call the db) then you don't need to use it.  
mysql_connect establishes a connection for the duration of the script that access the db. Once the script has finished executing it closes the connection. The only time you need to close the connection manually is if you jump out of the script for any reason.

If you do use mysql_pconnect. You only need to call it once for the session. That's the beauty of it. It will hold open a connection to the db that you can use over and over again simply by calling the resource ID whenever you need to interact with the db.

What is order by length in mysql?

+------+
| code |
+------+
| A10  |
| A20  |
| A5   |
| A6   |
| A7   |
| A8   |
| A9   |
+------+

You can query like this:
mysql> select * from table order by length(code), code;

+------+
| code |
+------+
| A5   |
| A6   |
| A7   |
| A8   |
| A9   |
| A10  |
| A20  |
+------+
  
Cheers! 

What is ORDER BY FIELD in mysql?

see you have a table name employee like below

table name employee

id   name      grade
1    Mahesh   A
2    Vikrant    B
3    Vikas       C
4    Pankaj     D

if you want to fetch these record in a specific order like D, B, C, A


then, you have to use ORDER BY FIELD clause in mysql.
 
 e.g.,

SELECT * FROM employee
ORDER BY FIELD(grade, 'D', 'B', 'C', 'A');

now the output of above query will be:


id   name      grade
4    Pankaj     D2    Vikrant    B
3    Vikas       C
1    Mahesh   A

Wednesday 14 April 2010

What is the difference between GROUP BY and ORDER BY in SQL?

To sort a result, use an ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).
ORDER BY [col1],[col2],...[coln]; Tells DBMS according to what columns it should sort the result. If two rows will have the same value in col1 it will try to sort them according to col2 and so on.
GROUP BY [col1],[col2],...[coln]; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.

Cheers!

What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, "Hello!" will be stored as "Hello! " in CHAR(10) column.

VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, "Hello!" will be stored as "Hello!" in VARCHAR(10) column.

Cheers!

What is the maximum length of a table name, a database name, or a field name in MySQL?

Database name: 64 characters
Table name: 64 characters
Column name: 64 characters

Cheers!

What is the difference between the functions unlink and unset?

unlink() is a function for file system handling. It will simply delete the file in context.

unset() is a function for variable management. It will make a variable undefined.


Cheers!

What Is a Persistent Cookie?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
  1. Temporary cookies can not be used for tracking long-term information.
  2. Persistent cookies can be used for tracking long-term information.
  3. Temporary cookies are safer because no programs other than the browser can access them.
  4. Persistent cookies are less secure because users can open cookie files see the cookie values.

Tuesday 13 April 2010

How To Close a Session Properly?

Let's say you site requires users to login. When a logged in user clicks the logout button, you need to close the session associated with this user properly in 3 steps:
  1. Remove all session values with $_SESSION = array().
  2. Remove the session ID cookie with the setcookie() function.
  3. Destroy the session object with the session_destroy() function.
Below is a good sample script:
<?php
  session_start();

  $_SESSION = array();

  if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-42000, '/');
  }

  session_destroy();

  print("<html><pre>");
  print("Thank you for visiting FYICenter.com.\n");
  print("  <a href=login.php>Login Again.</a>\n");
  print("</pre></html>\n");
?>

How To Set session.gc_maxlifetime Properly?

As you know that session.gc_maxlifetime is the session value timeout period. You should set this value based on the usage pattern of your visitors. Here are some suggestions:
# Set it to 20 minutes for a normal Web site:
session.gc_maxlifetime = 1200

# Set it to 24 hours if visitors comes to the site many time a day:
# Example: Yahoo email site expires your session in 24 hours.
session.gc_maxlifetime = 86400

How To Force the PHP Engine to Use Cookies to Transfer Session IDs?

f you want to force your PHP engine to use cookies to transfer session IDs instead of URL parameters, you can open the PHP configuration file, php.ini, and make the following changes:
session.use_cookies = 1
session.use_only_cookies = 1

How To Turn On the Session Support?

The session support can be turned on automatically at the site level, or manually in each PHP page script:
  • Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini.
  • Turning on session support manually in each page script: Call session_start() funtion.

What is FULLTEXT search in mysql?

FULLTEXT search is used to search the data from Mysql.

Once you have a FULLTEXT index, you can search it using MATCH and AGAINST statements.
For example:
 
SELECT name, title FROM news
WHERE MATCH (name,title) AGAINST ('google');
 

MATCH

The MATCH function is used to specify the column names that identify your FULLTEXT collection. The column list inside the MATCH function must exactly match that of the FULLTEXT index definition, unless your search in boolean mode (see below).

AGAINST

The AGAINST function is where your full text search query goes. Besides the default natural language search mode, you can perform boolean mode searches, and use query expansion.


FULLTEXT search works only datatype varchar and text.  also, with MYISAM table type.


Restrictions

A few restrictions affect MySQL FULLTEXT indices. Some of the default behaviors of these restrictions can be changed in your my.cnf or using the SET command.
  • FULLTEXT indices are NOT supported in InnoDB tables.
  • MySQL requires that you have at least three rows of data in your result set before it will return any results.
  • By default, if a search term appears in more than 50% of the rows then MySQL will not return any results.
  • By default, your search query must be at least four characters long and may not exceed 254 characters.
  • MySQL has a default stopwords file that has a list of common words (i.e., the, that, has) which are not returned in your search. In other words, searching for the will return zero rows.
  • According to MySQL's manual, the argument to AGAINST() must be a constant string. In other words, you cannot search for values returned within the query.




 
 
Cheers!

What is Final Keyword?

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.


<?php 
class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() called\n";
   }

   final public function 
moreTesting() {
       echo 
"BaseClass::moreTesting() called\n";
   }
}

class 
ChildClass extends BaseClass {
   public function 
moreTesting() {
       echo 
"ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()

?>  


Similarly, You can stop overriding class using FINAL keyword. e.g., 


<?php
 final class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() called\n";
   }

   
// Here it doesn't matter if you specify the function as final or not
   
final public function moreTesting() {
       echo 
"BaseClass::moreTesting() called\n";
   }
}

class 
ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass) 

?>

 


Cheers!

Difference between CURL and FILE_GET_CONTENT?

PHP offers two main options to get a remote file, curl and file_get_contents.
There are many difference between the two.
Curl is a much faster alternative to file_get_contents.

Cheers!

Where session stroe?

The file format is so simple, session data is stored in clear text, with ";" as delimiters. If you want to change where session data is stored, you can modify the session.save_path setting in \php\php.ini. For example:
session.save_path = "\herong\temp"

How to store session variables?

<?php
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve session data
?>

Cheers!

What is Session?

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.


A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.


Friday 9 April 2010

How to Declare a Class and Initializing a Class Object ?

Declaring Class in PHP5:
In PHP5 you create a new class using "class" keyword.
The basic declaration of a class:


class myClass
{
   public function getAge()
   {
      echo "Inside Method";
   }
}
 
Initializing an Class Object in PHP5

To access the class from the outside world i.e. outside the scope of
class; you will need to create an object instance of the class. This
can be achieved using "new" operator.

Initializing Class 

class myClass
{
   public function myAge()
   {
      echo "Inside Method";
   }
}     
$myClassObj = new myClass();
 
//Calling class method... 
$myClassObj->myAge(); 

How to check Session is expire or not during Aajx Call?

As I told you in my previous post, there are some status code you found in during Ajax Call.
 
if(xmlhttp.status == 500) {
// That means session has been lost..
// Do your task whatever you want to do here... 
}
Cheers!

Difference b/w Synchronous and Asynchronous?

Suppose there are two process A and B are running and process B are depends upon the process A result.

If two processes are running Synchronously, it means that second process will wait until or unless first process complete.

If two processes are running Asynchronously, it means second process will not wait for second process result and will be executed.

Cheers!

Some Important Tips on Ajax

By default in a open method, you found something like this:
open("GET",url,false);

method: the type of request: GET or POST
url: the location of the file
boolean: true (asynchronous) or false (synchronous)

Here last parameter is false it means process will be synchronous.

To make process Asynchronous, make true instead of false.

Cheers!

What is the Status means in Ajax term?

Whenever response return it also return status.

for example:

if (xmlhttp.status == 200) // i.e., OK
if (xmlhttp.status == 404) // i.e., Page not found.
if (xmlhttp.status == 500) // i.e., Session expired.

Cheers!

What are the means of readyState in Ajax

There are four type of readyState exist in Ajax:

0: not initialized.
1: connection established.
2: request received.
3: answer in process.
4: finished. 
 
 
Cheers! 

Wednesday 7 April 2010

What is the difference between the functions unlink and unset?

unlink() is a function for file system handling. It will simply delete the file in context.

unset() is a function for variable management. It will make a variable undefined.

Cheers!

What are the different types of errors in PHP?

Here are three basic types of runtime errors in PHP:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior.

2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.


Cheers!

How do I find out the number of parameters passed into function?

PHP provides a function name func_num_args() which returns the number of parameters passed in.

for example:

<?phpfunction foo()
{
    
$numargs func_num_args();
    echo 
"Number of arguments: $numargs\n";
}
foo(123);    // Prints 'Number of arguments: 3'?>


Cheers!

How can we get the Uploaded File Information in the Receiving Script?

PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array like:
$_FILES[$fieldName]['name'] - The Original file name on the browser system.
$_FILES[$fieldName]['type'] - The file type determined by the browser.
$_FILES[$fieldName]['size'] - The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error'] - The error code associated with this file upload.

The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.

Cheers!

What are the MySQL database files stored in system ?

There are 3 type of files stored in system whenever you create a database.

suppose you create a database name like necourse.db

then following files will be created:

Data is stored in newcourse.myd
Table structure is stored in newcourse.frm
Index is stored in newcourse.myi

cheers!

Tuesday 6 April 2010

How __autoload() does?

Autoload is a new feature introduced in PHP5 that you don't have to explicitly require or include a PHP script file that contains the class being used any more but it will be automatically loaded or included when needed.

For example, with PHP4 you would have to write something like this:

require_once("foo.php"); // foo.php contains the class Foo
myFoo = new Foo();

Every time you need to create an object of some class you have to include/require the particular PHP file
that contains that class.
It can be a challenge to manage the whole lot of include or require lines as well.
That's where the autoload feature of PHP5 kicks in.

Instead of including a particular PHP script every time we need it, we create a very simple function at the beginning of the current file so that PHP automatically knows what file to include when we need a particular class.
For example:
function __autoload($className)
{
    require_once 'includes/classes/'. $className. '.php';
}

$obj1 = new MyNewClass1(); // PHP automatically requires 'includes/classes/MyNewClass1.php'
$obj2 = new MyNewClass2(); // PHP automatically requires 'includes/classes/MyNewClass2.php'

Thursday 1 April 2010

How to add CSS in drupal?

<?php
 // Repeat this line for every CSS file added. 
drupal_add_css(path_to_theme() . '/example.css', 'theme', 'all', TRUE); 
 // Reassemble the $styles snippet to include the new files. 
$styles = drupal_get_css(); 
?>
Enjoy Drupaling.
Cheers!

What are the Pre-Defined Variables that drupal provides?

Available variables

$base_path:
Returns the base URL path of the Drupal installation. At the very least, this will always default to /.
$breadcrumb:
HTML for displaying the breadcrumbs at the top of the page.
$closure:
Needs to be displayed at the bottom of the page, for any dynamic javascript that needs to be called once the page has already been displayed.
$content:
The HTML content generated by Drupal to be displayed.
$css:
An array of all the CSS files for the current page.
$directory:
The directory the theme is located in, e.g.
themes/garland or themes/garland/minelli.
$feed_icons:
A string of all feed icons for the current page.
$footer_message:
The footer message as defined in the admin settings, also the HTML for the footer region.
$head:
HTML as generated by drupal_get_html_head().
$head_title:
The text to be displayed in the page title.
$header:
HTML for the header region.
$help:
Dynamic help text, mostly for admin pages.
$is_front:
True if the front page is currently being displayed. Used to toggle the mission.
$language:
The language the site is being displayed in.
$layout:
This setting allows you to style different types of layout ('none', 'left', 'right' or 'both') differently, depending on how many sidebars are enabled.
$logo:
The path to the logo image, as defined in theme configuration.
$messages:
HTML for status and error messages, to be displayed at the top of the page.
$mission:
The text of the site mission, empty when display has been disabled in theme settings.
$node
(5.x and after only) If you are in page.tpl.php displaying a node in full page view then $node is available to your template.
$onload_attribute:
(4.7 and older only) Onload tags to be added to the head tag, to allow for autoexecution of attached scripts.
$primary_links (array)
An array containing the links as they have been defined in the phptemplate specific configuration block.
$scripts:
(5.x and after only) HTML to load the JavaScript files and make the JS settings available. Previously, javascript files are hardcoded into the page.tpl.php
$search_box:
True(1) if the search box has been enabled.
$search_button_text:
(4.7 and older only)Translated text on the search button.
$search_description:
(4.7 and older only)Translated description for the search button.
$search_url:
(4.7 and older only)URL the search form is submitted to.
$secondary_links (array):
An array containing the links as they have been defined in the phptemplate specific configuration block.
$sidebar_left:
The HTML for the left sidebar.
$sidebar_right:
The HTML for the right sidebar.
$site_name
The name of the site, empty when display has been disabled in theme settings.
$site_slogan:
The slogan of the site, empty when display has been disabled in theme settings.
$styles:
Required for stylesheet switching to work. This prints out the style tags required.
$tabs:
HTML for displaying tabs at the top of the page.
$title:
Title, different from head_title, as this is just the node title most of the time. Enjoy Drupaling. Cheers!

Wednesday 31 March 2010

Check out who else current user is logged in?

<?php
if ($GLOBALS['user']->uid
{
 
  echo $GLOBALS['user']->uid;
 
} ?>
 
 
Enjoy Drupaling.
Cheers!
 

How to make search enginers compatible URL in drupal?

Use PathAuto and Path Redirect together to redirect old aliases to the new ones.
Search engines will use each page as a single page.

Enjoy Drupaling!

Cheers!

Tuesday 30 March 2010

Admin login problem exist after installation in magento?

Hi All,
 
Use the following URL to login 
http://localhost/magento/index.php/admin 
 
if does not work then use the another way to login 
 
 

OR 
 
Open Varien.php file using the following path: 
 
app\code\core\Mage\Core\Model\Session\Abstract\Varien.php
 
find the below given code in above file:
if (isset($cookieParams['domain'])) {
    $cookieParams['domain'] = $cookie->getDomain();
}
 


Replace If condition with the below if condition:

if (isset($cookieParams['domain']) && !in_array("127.0.0.1", self::getValidatorData())) {







 
And done!
 
 

Cheers!

 


How to enable CURL extension in your PHP?

There are few steps through which you can find CURL extension is enbaled in your PHP or not:

These are the steps to take:

1. open a blank text document.

2. copy and paste this code into notepad and save it as test.php

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

4. If there was an error, then it means that you do not have this extension enabled. and you will see an error similar to this one:
Fatal error: Call to undefined function curl_version() in test.php on line 2

5. Open your php.ini file and look for this line:
;extension=php_curl.dll

path: php > php.ini

Remove ; before the extension word and done!

your curl has been enabled.

Restart your server.

Cheers!

How to restart Apache and Mysql using Putty?

Apache Restart
/etc/init.d/httpd restart

# To Start MySQL Server
/sbin/service mysqld start

# To Stop MySQL Server
/sbin/service mysqld stop


Cheers!