Oct 29, 2011

A Good PHP Developer Can Answer This | PHP Test

PHP developers go through 3 stages in their life

  • Beginner

  • Good

  • Best

A beginner PHP coder is some one who just started making some PHP projects in CMS like Wordpress, Joomla, Magento and other PHP based CMS.

A good PHP coder completed or knows all PHP based CMS and is about to finish PHP Frameworks like Yii, Cake, Symphony, CI and others.

A best PHP coder is a complete package of Beginner and Good, that person needs no questions cause he might be ready with all the answers.

Now its time to rate yourself in PHP, I googled and found some questions which only a Good coder can answer.

A: Its the scope resolution operator (double colon ::). This is valid for PHP 4 and later only.

Q2: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Reason: body data was sent, causing headers to be sent too. This normally occurs when white space is sent accidentally.

Q3: What's wrong in this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: This is the worst practice to select some row or fetch data, use specific row instead of *. Use PDO prepared statements to avoid SQL Injections.

Q4: What is wrong with this if statement: if( !strpos( $thread, $needle ) ...?
A: strpos returns the index position of needle, it could return false if its at 0 position. Instead give a if else check if( false !== strpos( $thread, $needle )...

Q5: What is the preferred way to write this if statement, and why?
if( 5 == $someVar )
or if( $someVar == 5 )
A: The former, it prevents accidental assignments of 5 to $somevar if you forgot two == signs(if( $someVar = 5 ))

Q6: In the below code, whats the value of $a and $b after the function call and why?

function doSomething( &$arg )
$return = $arg;
$arg += 1;
return $return;

$a = 3;
$b = doSomething( $a );

A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.

Q7: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.

Q8: What is wrong with this code:

class SomeClass
protected $_someMember;

public function __construct()
$this->_someMember = 1;

public static function getSomethingStatic()
return $this->_someMember * 5; // here's the catch


A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.

Q9: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.

Q10: Which one is correct?: $array[name] or $array['name']?
A: Both of them will output the value, but only the quoted form is correct. To check this define(name,0); and see the bugs flying in the website.

Now how much did you score out of 10, comment your score below, and if you have any more questions then let me know after all sharing is caring ;)

Oct 26, 2011

Insert Record Into Database Using AJAX | How To Insert Data Into Database Using AJAX

In todays tutorial, I am going to teach you, HOW AJAX WORKS. This tutorial is good for people who are seeking on internet to learn AJAX with PHP and MYSQL.

I am going to share a AJAX Driven tutorial with you, in which we will insert a record in our Database through AJAX, which means data will be added into database, without refreshing the page and we will also show the added values.

So lets start this, first we need to setup a folder structure.
Make a folder and inside it, add three files,

  • index.php

  • data.php

  • ajax.gif

Now we will add basic html code into our index.php file


<div id="wrapper">
<input type="text" id="name" value="Your Name" />
<input type="button" value="Submit" onclick="addRecord()" />
<div id="propspectDiv"></div>
<table id="data" border="1" cellspacing="0" cellpadding="0" width="75" style="display:none;"></table>



Now comes the main AJAX code.

Inside your head tag, add the following code:


<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

function addRecord()
var term_name = $('#name').val();        //Storing the value of textbox into a variable

if(term_name == '')        //Checking for NULL
$('#propspectDiv').html('Enter A Valid Name');    //Prints the progress text into our Progress DIV
$('#name').addClass('error');                    //Adding the error class to the progress DIV
$('#propspectDiv').removeClass('error'); //Removing the error class from the progress DIV
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');//Prints the progress text into our Progress DIV

url : 'data.php', //Declaration of file, in which we will send the data
"name" : term_name                //we are passing the name value in URL
success : function(data){
$('#propspectDiv').html('Your Name is added to our records'); //Prints the progress text into our Progress DIV
$('#data').css("display","block");  //Changes the style of table from display:none to display:block
$('#data').html(data);                //Prints the data into the table
}, 2000);




In our AJAX function first we are storing the value of textbox in a variable.
Then we check whether the variable is not passed NULLED, if condition is satisfied, then it enters to a condition, where it adds some HTML code into progress div.

Finally we call our AJAX function, where we pass the "name" value to our file data.php through URL. data.php file echoes some values and inserts name into our database.

We call this echoed values and display it in our table.

data.php code


$name = $_REQUEST['name'];

$con = mysql_connect("localhost","root","");

mysql_select_db("test", $con);

$sql = 'INSERT INTO `test`.`name` (`ID`, `Name`) VALUES (NULL,"'.$name.'")';

if (!mysql_query($sql,$con))
die('Error: ' . mysql_error());
$sqlnew = 'SELECT * from name;';
$res = mysql_query($sqlnew);
echo '<tr><th>Name:</th></tr>';
while($row = mysql_fetch_array($res))
echo '<tr><td>'.$row['Name'].'</td></tr>';



Here we are learning the basics of JQUERY AJAX, if you understand the main concept and the flow of AJAX with PHP, then with the help of google you can make many ajax driven programs.

Final Output:



Oct 25, 2011

How to use Views Slideshow in Drupal 7

1. Required Modules (Version: Drupal 7.8)

  1. Views (7.x-3.0-rc1)
  2. Views Slideshow (7.x-3.x-dev)
  3. Chaos tool suite (7.x-1.0-rc1)
  4. Libraries (7.x-1.0)
  5. Link (7.x-1.0)
  6. Token (7.x-1.0-beta6)

2. Install the Modules

In Drupal 7 you can install modules from the admin section, but I still feel this new feature doesn't have any meaning, because we have to search for the module link in the Drupal site and then copy paste into the admin module installation area, it would have been so good if they would have made it something like WordPress a small search feature. Anyway I just gonna download and install it in the old way (I still recommend this old way).
Download all the above listed modules from http://drupal.org/project and install in the directory examplesite.com/sites/all/modules

Go to http://www.examplesite.com/admin/modules and enable these modules as below:

Modules - Drupal
Enable Modules
  2. Views UI
  3. Views Slideshow
  4. Views Slideshow: Cycle
  5. Chaos tools
  6. Libraries
  7. Link
  8. Token

3. Create Image Cache

In Drupal 7 imagecache is part of core module and is named as Image styles. So let's create two image cache from here, one for the full size slider image and other for the thumbnail image. In this tutorial I use 640x480 (pixels) dimension for the full size slider image and 320x240 (pixels) dimension for the thumbnail image. Note: These configurations can be defered depends on your needs.

Fullsize Slider image settings

Go to http://www.examplesite.com/admin/config/media/image-styles and click on the add new style link

  1. Give an Image style name and click on create new style button.
  2. On the next configuration screen select new style you want and then click add button (In this tutorial I choose re-size style).
  3. On the next screen set the width and height and click on the add effect button. (The settings may vary depend on the style you choose). I set width as 640 and height as 480 pixels.
  4. Do this same process for the thumbnail image too. (for the thumbnail image dimension, I set width as 320 and height as 240 pixels.)

4. Create New Content Type

Let's create a new content type, from the dashboard menu bar cick on Structure and then Content types then click on the add new content type link.

  1. Give a human-readable name, I named it as Featured Slider (machine name will be auto generated based on the human readable name)
  2. Give a brief and relevant description
  3. Submission form settings, I leave as the default settings
  4. Publishing options, I checked only published (all other settings unchecked)
  5. Display settings, I have unchecked the authour and date info.
  6. Comment settings, I set hidden (disabled)
  7. Menu settings, I leave as default settings.
  8. Click Save and add fields Button

5. Create New Fields

Here in this example I'll create only two fileds, and they are image field and link field. We will use image field for uploading our slider image and link field for creating a custom link where we want our slider to be linked.

  1. Image Field Settings
  2. Label: Slider Image
  3. Field: slider_image
  4. Field type: image
  5. Widget (form element): image
  6. Click Save button, and on the field settings page leave default settings and click on Save field settings button.
  7. On the image field configuration settings page you can configure as you wish.
  • I set this field as required, I added a file director name called slider-image so that this images will be arranged separately from other images.
  • You can set the maximum upload size and resolution here, I have enabled alt and title field and finally click Save settings button.

By using same method create the link field too.

Link Field Settings:

  1. Label: Slider Link
  2. Field: slider_link
  3. Field type: link
  4. Widget (form element): link
  5. Click "Save" button

Note: For the link field configurations leave everything to default settings.

I have re arranged the field like shown below:

  • Title field
  • Image field
  • Link field
  • Body field (you can even remove this field if not necessary)

Manage Display

On the manage display tab you can conigure how the out put of the field to be diplayed, I have set the image label as hidden.

6. Create Feature Slider Content

I have created four featured slider content for this tutorial.

  1. Click on add content link
  2. Create Featured Slider content
  3. Give a proper title name
  4. Upload slider image
  5. Give alt and title field names
  6. Give a link title and url where you want the slider to be linked
  7. Leave all othe settings as default except for the path field if you want you can give an SEO friendly URL alias.
  8. Save the content.

Repeat the steps twice or thrice to create some more featured slider contents for your slide (I have created four contents)

7. Create a New View

Now it's time to create our new Slideshow view. From the Dashboard menu click on the Structure and then click on the Views.

  1. Click add new view link
  2. Give view name, I have named as Featured Slider (machiine name will be auto generated)
  3. Give an apropriate view description
  4. Choose Show Content of type Featured Slider (your content type name).
  5. Uncheck Create a Pge and check Create a block
  6. Type in Block title and choose display format as "Slideshow" of "fields" items per page 5 (you can enter the number of items you want to display)
  7. Click the button "Continue & edit"

Views Field Settings

  • Add "Link" Field
  1. "Link" must be the first field in order to work everything properly, so click on the add icon and from the filter Groups select "Content"
  2. Add Content: "Link" "Appears in: node:featured_slider."
  3. Click: "Add & configure button"
  4. In the next cofiguration window uncheck "Create a label" and check "Exclude from display"
  5. Click "Apply button".
  • Add "Image" Field
  1. Click on the add icon and from the filter Groups select "Content"
  2. Add Content: "Image" "Appears in: node:featured_slider." (Note: Make sure you choose the "Image" field which we created for this slider content type only.)
  3. Click "Add & configure button"
  4. In the next cofiguration window uncheck "Create a label"
  5. Formatter: "Image" (If you have installed "Colorbox" or "Lightbox2" you can choose them here.)
  6. Image Style: "Fullsize" (Choose the imagecache you have created in the above step "3. Create Image Cache")
  7. Link image to: "Nothing"
  8. Style Settings: "Leave default settings"
  9. No result behaviour: "Leave default settings"
  10. Rewrite Results: Check "Output this field as a link"
  11. Link path: [view_node] (Note: Scroll dow a bit and you can see replacement patterns created by Token module, (If we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
  12. Click "Apply button".
  • Add "Thumbnail" Field
  1. Click on the add icon and from the filter Groups select "Content"
  2. Add Content: "Image" "Appears in: node:featured_slider." (Note: Make sure you choose the "Image" field which we created for this slider content type only.)
  3. Click "Add & configure button"
  4. In the next cofiguration window uncheck "Create a label" and check "Exclude from display"
  5. Formatter: "Image" (If you have installed "Colorbox" or "Lightbox2" you can choose them here.)
  6. Image Style: "Thumbnail" (Choose the imagecache you have created in the above step "3. Create Image Cache")
  7. Link image to: "Nothing"
  8. Style Settings: "Leave default settings"
  9. No result behaviour: "Leave default settings"
  10. Rewrite Results: Check "Output this field as a link"
  11. Link path: [view_node] (Note: Scroll dow a bit and you can see replacement patterns created by Token module, (If we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
  12. Click "Apply button".

Views Filters Settings

In Views 3.x the filters are created in the beginning while we choose the content type and other settings. If you need any additional filtering you can create it here.

Views Style Settings

Click on the "Format Slideshow Settings" and on the next configuration window set as below:

  • List type: "Unordered list"
  • Wrapper class: "Leave default settings"
  • Style » Skin: "Deafult"
  • Slides » Slideshow type: "Cycle"

"Cycle Options"

You need to download jQuery cycle plugin and copy jquery.cycle.all.min.js to sites/all/libraries/jquery.cycle You can find the plugin at http://malsup.com/jquery/cycle.

In a Simpler Manner

Create a folder named "libraries" in your "examplesite.com/sites/all/" directory and then create an another folder named "jquery.cycle" in that directory and finally copy and paste only the "jquery.cycle.all.min.js" into this directory. For e.g. examplesite.com/sites/all/libraries/jquery.cycle/jquery.cycle.all.min.js

  • Transittion: "Fade"
  • Action: "Pause on Hover"
  • Internet Explorer Tweaks: "Default"
  • Widgets: You can choose either or both Top and Bottom (I choose bottom here, and the advance settings as below:)
  • Bottom Widgets » Pager » Pager type: "Fields"
  • Pager field » Content: "Image" (Note: Last one we added for the thumb, don't mistake since both field will be named same.)
  • Activate Slide and Pause on Pager Hove: Checked » "Controls" and Unchecked » "Slider Counter"
  • Click on "Apply button".

Format Show Field Settings

  • Inline fields: "Choose the thumbnail field as inline."
  • Click on "Apply button." (Note: Well it actually doesn't change much in appearance but it does change in the code.)

8. Enable & Configure the Block

Now this block will be visible in the blocks disabled area, so from the Dashboard menu go to Structure » Block and "Enable" the block to a themes default region or any of the custom region you've created. (Regions varies depends on the theme you are using.)

Block Configuration Settings

After enabling the block you get a link to configure the block so click on the "Configure" link and on the settings section set as below;

  • Block title (If you don't want block title to be displayed just type <none>)
  • Again you get all enabled theme specific Region settings.

On Visibility Setings

  • Pages » Show block on specific page: choose Only the listed pages and typeso that this block will be displayed only on the front page.

Oct 21, 2011

PHP Multidimensional Array Shuffle | Shuffle Array In PHP

Multi-Dimensional array is an array within array. It is the most common used php function to store multiple values within a variable.

Here is my small snippet share for shuffling multidimentional array values.

Just call this function and pass the multidimensional array through parameters.

[php]public static function shuffle_array($array)
if (!is_array($array)) return $array;
$keys = array_keys($array);
$random = array();
foreach ($keys as $key) {
$shuffle[] = $array[$key];
return $shuffle;

Oct 7, 2011

Must have modules for creating a site in Drupal 7.x


This suite is primarily a set of APIs and tools to improve the developer experience. It also contains a module called the Page Manager whose job is to manage pages. In particular it manages panel pages, but as it grows it will be able to manage far more than just Panels.

Custom Breadcrumbs

Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.

No new features are planned for these versions, but they are still supported and bug reports are encouraged.


The Fivestar voting module adds a clean, attractive voting widget to nodes in Drupal 5, node and comments in Drupal 6, and any entity in Drupal 7


The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.


The Pathauto module automatically generates path aliases for various kinds of content (nodes, categories, users) without requiring the user to manually specify the path alias. This allows you to get aliases like /category/my-node-title.html instead of /node/123. The aliases are based upon a "pattern" system which the administrator can control.


This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.

The process of stemming reduces each word in the search index to its basic root or stem (e.g. 'blogging' to 'blog') so that variations on a word ('blogs', 'blogger', 'blogging', 'blog') are considered equivalent when searching. This generally results in more relevant search results.


The rules modules allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).


Tokens are small bits of text that can be placed into larger documents via simple placeholders, like %site-name or [user]. The Token module provides a central API for modules to use these tokens, and expose their own token values.


The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Traditionally, Drupal has hard-coded most of this, particularly in how taxonomy and tracker lists are formatted.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content.


Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.