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!