Monday, November 19, 2012

Keyword Serach in DB Mysql

<?php
function searchAllDB($search){

    global $mysql;

    $out = "";

    $sql = "show tables";
    $rs = mysql_query($sql);
    $num = mysql_num_rows($rs);
    if($num > 0){
   
        while($r = mysql_fetch_array($rs)){
           
           
            $table = $r[0];
            $out .= $table.";";
            $sql_search = "select * from ".$table." where ";
            $sql_search_fields = Array();
            $sql2 = "SHOW COLUMNS FROM ".$table;
            $rs2 = mysql_query($sql2);
             $num2 = mysql_num_rows($rs2);
            if($num2 > 0){
                while($r2 = mysql_fetch_array($rs2)){
               
           
                    $colum = $r2[0];
                    $sql_search_fields[] = $colum." like('%".$search."%')";
                }
                //$rs2->close();
           }
                // echo'<pre>';
            // print_r($sql_search_fields);
            // echo'</pre>';
            $sql_search .= implode(" OR ", $sql_search_fields);
            $sql_search .=';';
            $rs3 = mysql_query($sql_search);
            $res3 = mysql_fetch_assoc($rs3);
           
            echo'<pre>';
            print_r($res3['entity_id']);
            echo'</pre>';
           
        }
      //  $rs->close();
    }

    return $out;
}

searchAllDB('test');



?>

Wednesday, August 22, 2012

What is the difference between $form & $form_state in Drupal

I am working with drupal 7 really its crazy but some how i confused  in drupal $form & $form_state

I discussed with many people now i got some clarification on this $form & $form_state values.$form defines the form, $form_state carries information about the processed form.

How to validate froms in Drupal 7?

Drupal Form validations

Here you can get the form values from form_state 

Below is the simple example for form validations  

function test_form_validate($form, &$form_state) {
  if (
$form_state['values']['name'] == '') {
    
form_set_error('name', t('You must select a name for this group of settings.'));
  }
}

Drupal 7 Basic form with submit handler

Bellow code tells about the basic form submit in drupal7

<?php
function my_module_menu() {
 
$items = array();
 
$items['my_module/form'] = array(
   
'title' => t('My form'),
   
'page callback' => 'my_module_form',
   
'access arguments' => array('access content'),
   
'description' => t('My form'),
   
'type' => MENU_CALLBACK,
  );
  return
$items;

}

function my_module_form() {
  return
drupal_get_form('my_module_my_form');
}


/*
  # Sample registration form 
*/
function my_module_my_form($form_state) {
 
$form['name'] = array(
   
'#type' => 'fieldset',
   
'#title' => t('Name'),
   
'#collapsible' => TRUE,
   
'#collapsed' => FALSE,
  );
 
$form['name']['first'] = array(
   
'#type' => 'textfield',
   
'#title' => t('First name'),
   
'#required' => TRUE,
   
'#default_value' => "First name",
   
'#description' => "Please enter your first name.",
   
'#size' => 20,
   
'#maxlength' => 20,
  );
 
$form['name']['last'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Last name'),
   
'#required' => TRUE,
  );
 
$form['year_of_birth'] = array(
   
'#type' => 'textfield',
   
'#title' => "Year of birth",
   
'#description' => 'Format is "YYYY"',
  ); 
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => 'Submit',
  );
  return
$form;
}


function my_module_my_form_validate($form, &$form_state) {
   
$year_of_birth = $form_state['values']['year_of_birth'];
    if (
$year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
      

  form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
    }
}


 function my_module_my_form_submit($form, &$form_state) {
   
drupal_set_message(t('The form has been submitted.'));
}


?>

Wednesday, August 15, 2012

Drupal 7 Confirm Password form alter example

Description: Format a pair of password fields, which do not validate unless the two entered passwords match.
 
<?php
$form
['pass'] = array(
  '#type'
=> 'password_confirm',
  '#title'
=> t('Password'),
  '#size'
=> 25,
);
?>

How to create checkboxes in Drupal form alter?

Description: Format a set of checkboxes. #options is an associative array, where the key is the #return_value of the checkbox and the value is displayed. The #options array cannot have a 0 key, as it would not be possible to discern checked and unchecked states.
 
<?php
$form
['high_school']['tests_taken'] = array(
  
'#type' => 'checkboxes',
  
'#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  
'#title' => t('What standardized tests did you take?'),
...
),
?>
 
 

Monday, July 30, 2012

NTLM Configaration Windows

Step1:- Download mod_auth_sspi-1.0.4-2.2.2 from google
Step2:- Install mod_auth_sspi.so module in apache modules folder
Step3 :- LoadModule sspi_auth_module modules/mod_auth_sspi.so   in httpd.conf file
Step4 :-   Add below code to httpd.conf file
        <Directory "C:/Program Files/BitNami WAMPStack/apps/htdocs/itscrefresh">
       Options Indexes FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
       AuthName "NTLM"
       AuthType SSPI
       SSPIAuth On
       SSPIAuthoritative On
       SSPIDomain Domain name
       SSPIOfferBasic On
       SSPIBasicPreferred On
       require valid-user
       </Directory>
 
Step5 :- Restart apache server and check

Monday, June 25, 2012

How to import Node Data with CCK in Drupal 7?

As per my requirement i need node data import with CCK

Steps:-
  1. First i created User defined content type with the use of CCK module.
  2. Need to Feed Module   http://drupal.org/project/feeds
  3. Need to install all the dependent modules
  4. Need to configure feed import module 
  5. Need to mapping CCK fields to CSV or XLS configaration
  6. Goto front-end and import CSV or XLS files    
  Enjoy the D7 feeds module :)

If you have any queries feel free to comment on my post


    

Tuesday, June 19, 2012

What is Node in Drupal

Node module manages the creation, editing, deletion, settings, and display of the main site content. Content items managed by the Node module are typically displayed as pages on your site, and include a title, some meta-data (author, creation time, content type, etc.), and optional fields containing text or other data

 Usage Node
Creating content
When new content is created, the Node module records basic information about the content, including the author, date of creation, and the Content type. It also manages the publishing options, which define whether or not the content is published, promoted to the front page of the site, and/or sticky at the top of content lists. Default settings can be configured for each type of content on your site.
Creating custom content types
The Node module gives users with the Administer content types permission the ability to create new content types in addition to the default ones already configured. Creating custom content types allows you the flexibility to add fields and configure default settings that suit the differing needs of various site content.
Administering content
The Content administration page allows you to review and bulk manage your site content.
Creating revisions
The Node module also enables you to create multiple versions of any content, and revert to older versions using the Revision information settings.
User permissions
The Node module makes a number of permissions available for each content type, which can be set by role on the permissions page.

What is Taxonomy in drupal7?

The Taxonomy module allows you to classify the content of your website. To classify content, you define vocabularies that contain related terms, and then assign the vocabularies to content types.

Best Example of USAGE :

Uses

Creating vocabularies
Users with sufficient permissions can create vocabularies and terms through the Taxonomy page. The page listing the terms provides a drag-and-drop interface for controlling the order of the terms and sub-terms within a vocabulary, in a hierarchical fashion. A controlled vocabulary classifying music by genre with terms and sub-terms could look as follows:
  • vocabulary: Music
    • term: Jazz
      • sub-term: Swing
      • sub-term: Fusion
    • term: Rock
      • sub-term: Country rock
      • sub-term: Hard rock
You can assign a sub-term to multiple parent terms. For example, fusion can be assigned to both rock and jazz.
Terms in a free-tagging vocabulary can be built gradually as you create or edit content. This is often done used for blogs or photo management applications.

Drupal 7 Top 10 Modules

Views
Create lists, tables, and feeds of content. This can be nodes, comments, users, or entities of any type.

Token
Use generic placeholders to display dynamic data. Token is usually installed as a dependency for another
module.

Pathauto
Automatically create search engine-friendly, human-readable URLs based on customizable patterns. An example URL alias is http://drupal.org/project/pathauto.

Administration Menu
Provides a horizontal, drop-down style administration menu at the top of each page, with links to all major administrative tasks.

Date
Creates a flexible date/time field and provides an API for other modules to use.

Google Analytics
Adds the Google Analytics web statistics tracking system to your site.

wysiwyg
Wysiwyg (What You See Is What You Get) provides a word processor-style content editor in the browser, similar to the interface of popular office applications like LibreOffice or Microsoft Office.

Webform
Create custom input forms for surveys, contest entry forms, contact forms, petitions and the like.

Chaos tool suite
Provides APIs and tools. This module is generally installed as a dependency of other modules.

Panels
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.

Drupal form alter Example

As per my requirement i need to change my node edit message

Find the below example

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'story_node_form') {    
    drupal_set_message(t('Editing a story node!'));
  }  }

What is Hook in Drupal?

Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook. Each hook has a defined set of parameters and a specified result type.

To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Wednesday, June 6, 2012

How to create Slideshow Module in Drupal 7?

This tutorial is now uptodate with latest modules!!!

(1) Required Modules (Version: Drupal7.0)

  1. Views (7.x-3.0-beta3)
  2. Views Slideshow (7.x-3.0-alpha1)
  3. Chaos tool suite (7.x-1.0-alpha4)
  4. Libraries (7.x-1.0)
  5. Link Field (7.x-1.0-alpha3)
  6. Token (optional) (7.x-1.0-beta1)

(2) Install the Modules

In Drupal7 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 Druapl site and then copy paste into the admin module installation area, really crazy. It would have been so good if they would have made it something like wordpress a small search feasture. Anyway I just gonna download and istall it in the old way (I still recommend this old way).
Download all the modules from Drupal site and install in the directory yoursitename/sites/all/modules.
Go to http://www.yoursitename.com/node#overlay=admin/modules and enable these modules as below;
(1) Views (2) Views UI (3) Views Slideshow (4) (5) Chaos tools (6) Link (7) Libraries (8) Token (Optional)

(3) Create Image Cache

In Drupal7 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 935x293 (pixels) dimension for the full size slider image and 210x100 (pixels) dimension for the thumbnail image. Note: These configurations csn be defered depends on your needs.
* Fullsize Slider image settings
Go to http://www.yoursitename.com/node#overlay=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 resize 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 935 and height as 293 pixels.
Do this same process for the thumbnail image too. (for the thumbnail image dimension, I set width as 210 and height as 100 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 (machiine 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 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.
 Image Field Settings
    (1) Label: Slider Image
    (2) Field: slider_image
    (3) Field type: image
    (4) Widget (form element): image
    (5) Click Save button, and on the field settings page leave default settings and click on Save field settings button.
    (6) 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 sperately from other images.
You can set the maximum upload size and resolution here, I have anabled 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,
For the link field configurations leave evrything 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 link field as hidden and I have also set image label as hidden
Drupal7: manage fields

(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 yo want you can give an SEO friendly URL alias.
  (8) Save the content.
Same way create more Featured Slider contents (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
First let's add link field (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
Add Content: Link, Click "Add & configure button" in the next cofiguration window uncheck "Create a label". "Check" Exclude from display.
Click "Apply button"
Next let's add image field, so click on the add icon and from the filter Groups select content
Add Content: image field (Note: make sure you choose the image field which we crerated for this slider content type only.)
Click "Add & configure button" in the next cofiguration window uncheck "Create a label".
Formatter: Image (if you have installed Colorbox or lightbox you can choose them here!)
Image Style: Fullsize (Choose the imagecache you have created in the above step)
Link image to: Nothing
Style Settings: Leave default settings
No result behaviour: Leave default settings
Rewrite Results: Check Output this field as a link
Link path: [view_node] (Note:Scroll dow a bit and you can see replacement patterns created by Core 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.)
Click "Apply button"
Finally we need one more field for the thumbnail, so let's click on the add icon and from the filter Groups select Content
Add Content: image field (Note: make sure you choose the image field which we crerated for this slider content type only.)
Click "Add & configure button" in the next cofiguration window uncheck "Create a label" and CHECK EXCLUDE FROM DISPLAY,
Formatter: Image (if you have installed Colorbox or lightbox you can choose them here!)
Image Style: Thumbnail (Choose the imagecache you have created in the above step)
Link image to: Nothing
Style Settings: Leave default settings
No result behaviour: Leave default settings
Rewrite Results: Check Output this field as a link
Link path: [view_node] (Note:Scroll dow a bit and you can see replacement patterns created by Core 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.)
Click "Apply button"
Views Filters Settings
In views3 the filters are created in the beginning while we choose the content type and other settings! If you need any additional filetering you can create it here!
Views Style Settings
Click on the Format Slideshow | settigs and on the next configuratioin window set as below;
  (1) List type: Unordered list
  (2) Wrapper class: Leave default settings
  (3) Style> Skin: deafult
  (4) Slides> Slideshow type: cycle
  (5) 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 SIMPLE ENGLISH
Create a folder named "libraries" in the site/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.
  (6) Transittion: Fade
  (7) Action: pause on hover
  (8) Internet Explorer Tweaks: default
  (9) Widgets: You can choose either or both Top and Bottom (I choose bottom here, and the advance settings as below;)
  (10) Bottom Widgets>Pager>Pager type: Fields
  (11) Pager field: Content: Image (Note: last one we added for the thumb, don't mistake since both field will be named same.)
  (12) Activate Slide and Pause on Pager Hove: checked, controls and slider counter leave unchecked.
  (13) Click Apply button.
Format Show Field Settings
  1. Inline fields: Choose the thumbnail field as inline.
  2. Click Apply button. (Note: Well it actually doesn't change much in appearance but it does change in the code. Next step use the firebug and find the class and add some styles to display properly.)

(8) Create a Custom Region (optional step)

(1) On your thems folder open the your_theme_name.info file and add a new region like this shown below;
regions[featured_slider] = Featured Slider and save the .info file.
(2) Open your themes page.tpl.php file and add these code where you want your slide to be displayed as shown below;
  <?php if ($page['featured_slider']): ?>
    <div id="featured-slider">
      <?php print render($page['featured_slider']); ?>
    </div> <!-- End Featured Slider-->
  <?php endif; ?>

You can even create custom front page template like page--front.tpl.php so that you do't need to make any changes to the default page.tpl.php template.

[9] 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 the custom region we created (featured_slider). (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;
  (1) Block title (if you don't want blobk title to be displayed just type <none>)
  (2) Again you get all enabled theme specific Region settings.
  On visibility setings
  (3) Pages>Show block on specific page: choose Only the listed pages and type <front> so that this block will be displayed only on the front page.

Friday, April 27, 2012

PHP Error Handling via htaccess

We can restrict PHP Errors via htaccess

PHP error handling for production servers

php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

php_flag display_errors off
php_flag html_errors off
 
# prevent access to PHP error log
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files> 

# PHP error handling for production servers
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/path/public_html/domain/PHP_errors.log
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1
php_value log_errors_max_len 0

<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

Thursday, April 26, 2012

How to fill an array with values specifying keys

array_fill_keysFill an array with values, specifying keys

<?php
$keys 
= array('foo'510'bar');$a array_fill_keys($keys'banana');print_r($a);?>


The above output

Array ( [foo] => banana [5] => banana [10] => banana [bar] => banana )  

Tuesday, April 24, 2012

document.formname.submit() is not a function or not working

When we are trying to submit a form using java script some times it will not working properly.

Find the below case

I have form like this

<form name="myform" method="post">
  <input type="text" name="name" value="">
  <input type="submit" name="submit" value="GO">
</form>

Here i am trying to submit the the form using java script
<script>
      document.myform.submit();
</script>

Error:- document.myform.submit() not a function

I have solution here change form submit name

<input type="submit" name="register" values="Go">

Don't put the form submit name as submit.





Number format in PHP

number_formatFormat a number with grouped thousands

<?php

$number 
1234.56;
// english notation (default)$english_format_number number_format($number);// 1,235

// French notation
$nombre_format_francais number_format($number2','' ');


?> 

Monday, April 23, 2012

How to create index in mysql table feild

We can create the index for table field very easily. Find the below code

ALTER TABLE `product_name` ADD INDEX ( `deal_id` ) ;

Explain advantages of MyISAM over InnoDB?


MyISAM table is stored in a separate files, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace etc

Explain advantages of InnoDB over MyISAM?

Row-level locking, transactions, foreign key constraints and crash recovery.

How to find number of unique values in table?

Using mysql query we can find the distinct values find the below query for your reffrence


SELECT COUNT (DISTINCT empname) FROM emp;

What are the different tables engines in MySQL

1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.

In how many ways we can retrieve the data in the result set of MySQL using PHP?

We can fetch the data from the database by 4 ways

1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc

What’s the default port for MySQL Server?

The Default port of mysql is: 3306

How to write IN query in mysql?

Suppose if you want to employee names from empl table who is having emp_id is 1,4,6 or 8

Check the below code for solution

SELECT emp_name FROM empWHERE emp_id IN (1, 4, 6, 8)

How do you get the number of rows affected by query?

SELECT COUNT (user_id) FROM users would only return the number of user_id’s.

How delete dublicate records in mysql table?

Find the following code using this code we can delete duplicate records

If you want to delete total dublicate records write check with the below code

delete from emp_sal USING emp_sal, emp_sal as vtable WHERE (NOT emp_sal.id=vtable.id) AND (emp_sal.sal=vtable.sal)

If you want to delete more one dublicate records check the below code

delete from emp_sal USING emp_sal, emp_sal as vtable WHERE emp_sal.id > vtable.id AND (emp_sal.sal=vtable.sal)

Thursday, April 19, 2012

How to add google search results to our website

The following code shows the google search results shows to our website

<!-- SiteSearch Google -->
<form method="get" action="http://home.wangjianshuo.com/archives/20060120_search_this_site.htm" target="_top">
<table border="0" bgcolor="#ffffff">
<tr><td nowrap="nowrap" valign="top" align="left" height="32">
<a href="http://www.google.com/">
<img src="http://www.google.com/logos/Logo_25wht.gif" border="0" alt="Google" align="middle"></img></a>
</td>
<td nowrap="nowrap">
<input type="hidden" name="domains" value="home.wangjianshuo.com"></input>
<input type="text" name="q" size="20" maxlength="255" value=""></input>
<input type="submit" name="sa" value="Search"></input>
</td></tr>
<tr>
<td> </td>
<td nowrap="nowrap">
<table>
<tr>
<td>
<input type="radio" name="sitesearch" value="" checked="checked"></input>
<font size="-1" color="#000000">Web</font>
</td>
<td>
<input type="radio" name="sitesearch" value="home.wangjianshuo.com"></input>
<font size="-1" color="#000000">home.wangjianshuo.com</font>
</td>
</tr>
</table>
<input type="hidden" name="client" value="pub-8513779941474461"></input>
<input type="hidden" name="forid" value="1"></input>
<input type="hidden" name="channel" value="6801625507"></input>
<input type="hidden" name="ie" value="ISO-8859-1"></input>
<input type="hidden" name="oe" value="ISO-8859-1"></input>
<input type="hidden" name="safe" value="active"></input>
<input type="hidden" name="flav" value="0000"></input>
<input type="hidden" name="sig" value="NdyQdGFpJnNH_B3d"></input>
<input type="hidden" name="cof" value="GALT:#008000;GL:1;DIV:#336699;VLC:663399;AH:center;BGC:FFFFFF;LBGC:336699;ALC:0000FF;LC:0000FF;T:000000;GFNT:0000FF;GIMP:0000FF;FORID:11"></input>
<input type="hidden" name="hl" value="en"></input>
</td></tr></table>
</form>
<!-- SiteSearch Google -->
Search Result Code
<!-- Google Search Result Snippet Begins -->
<div id="googleSearchUnitIframe"></div>
<script type="text/javascript">
var googleSearchIframeName = 'googleSearchUnitIframe';
var googleSearchFrameWidth = 650;
var googleSearchFrameHeight = 1300;
var googleSearchFrameborder = 0 ;
</script>
<script type="text/javascript"
src="http://www.google.com/afsonline/show_afs_search.js">
</script>
<!-- Google Search Result Snippet Ends -->

Thursday, April 12, 2012

Google Apps OPen ID with PHP

Google supports OpenID authentication or behaves as openid identity provider, using Google Apps accounts.
This is especially useful for companies to unite other internal services with Google Apps single sign-in point. This is related to Standard edition as well.

I have done my requirement with Google Apps OPEN-ID

Please go through with below URLS. You will get the solution

http://a32.me/2010/02/google-apps-premier-federated-login-with-php/ 

Tuesday, April 10, 2012

ereg is deprecated` errors in PHP 5.3+

If your working with PHP 5.3 or heighter, chances are high you’re going to run into a few warnings or deprecated function messages.
  
TO
ereg
('\.([^\.]*$)', string $string [, array &$regs ] );

Change 
preg_match('/\.([^\.]*$)/', $subject$matches);

How to send an error messages one log using PHP?

error_logSend an error message somewhere

error_log("You messed up!"3"/var/tmp/my-errors.log");

 

error_reporting in PHP?

<?php
// Turn off all error reportingerror_reporting(0);
// Report simple running errorserror_reporting(E_ERROR E_WARNING E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR E_WARNING E_PARSE E_NOTICE);
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL E_NOTICE);
// Report all PHP errors (see changelog)error_reporting(E_ALL);
// Report all PHP errorserror_reporting(-1);
// Same as error_reporting(E_ALL);ini_set('error_reporting'E_ALL);
?>

Sunday, April 8, 2012

Difference between Php4 and Php5

Find the below major changes in PHP4 & PHP5
  • PHP 5, the object model was rewritten to allow for better performance and more features
  • We can define abstract class
  • public,private and protected methods interdused
  • we can pass values by reffrence
  • In PHP5 new array functions are interduced
  • PHP 5 are the inclusions of Visibility, Abstract, Final Classes and method magic methods, interfaces, cloning,typehinting etc
  • New error level named E_STRICT has been introduced.
     
     
     

How to exchange all keys with their associated values in PHP?

array_flipExchanges all keys with their associated values in an array

<?php
$trans
= array("a" => 1, "b" => 1, "c" => 2);$trans = array_flip($trans);print_r($trans);?>
 
o/p:-
 
Array
(
    [1] => b
    [2] => c
)
 

Friday, April 6, 2012

HTML5 - Advantages

Find the below advantages?
  1. No longer we have to rely upon third party plug-in in order to render audio/video
  2.  HTML5 removes the need for JavaScript solutions
  3. HTML5 in mobile devices Advanced web application features are available in all mobile browsers supporting the markup language, using the same standard syntax and displaying the same standard behavior.

HTML5 vision

  1. HTML5 improves interoperability and reduces development costs by making precise rules on how to handle all HTML elements, and how to recover from errors.
  2.  Some of the new features in HTML5 are functions for embedding audio, video, graphics, client-side data storage, and interactive documents. 
  3.  HTML5 also contains new elements like <nav>, <header>, <footer>, <figure>…
  4.  The HTML5 working group includes AOL, Apple, Google, IBM, Microsoft, Mozilla, Nokia, Opera, and many hundreds of other vendors.
Note: HTML5 is not a W3C recommendation yet!

how to reads entire file into string?

file_get_contents();
file_get_contentsReads entire file into a string

<?php
$homepage
= file_get_contents('http://www.example.com/');
echo
$homepage;?> 



How To Create a WordPress Theme

Creating a WordPress Theme HTML Structure
Now we’re starting to get into the real meat of WordPress Theme development: coding the HTML structure.
The HTML Structure for Your WordPress Theme
Let’s take a look at the HTML structure we’ll be using for the body of our WordPress Theme.
<html>
<head>
</head>

<body>
<div id="wrapper" class="hfeed">
    <div id="header">
        <div id="masthead">

            <div id="branding">
            </div><!-- #branding -->

            <div id="access">
            </div><!-- #access -->

        </div><!-- #masthead -->
    </div><!-- #header -->

    <div id="main">
        <div id="container">

            <div id="content">
            </div><!-- #content -->

        </div><!-- #container -->

        <div id="primary" class="widget-area">
        </div><!-- #primary .widget-area -->

        <div id="secondary" class="widget-area">
        </div><!-- #secondary -->
    </div><!-- #main -->

    <div id="footer">
        <div id="colophon">

            <div id="site-info">
            </div><!-- #site-info -->

        </div><!-- #colophon -->
    </div><!-- #footer -->
</div><!-- #wrapper -->
</body>
</html>
   
WordPress Theme Template & Directory Structure
While the most minimal of WordPress Themes really only needs an index.php Template and a style.css file (or just the style file if it’s a Child Theme) most WordPress Themes need something a little more solid.
Our new minimal will include 6 files. Make a folder in wp-content/themes/ for your theme—for this tutorial I’ll be using “your-theme” but it can be whatever you want—and create the following files in that new folder (don’t worry, they’ll be blank until the next few steps).
•    index.php
•    header.php
•    sidebar.php
•    footer.php
•    functions.php
•    style.css
Now let’s open up the last file we created, style.css, in a text editor. The first thing we need to do is add a section at the top of this file bracketed by what are called CSS “comments” (these guys: /* and */). It’s here that we need to put the info that tells WordPress about your theme. Without it, your theme won’t show up in the themes panel.

Sunday, April 1, 2012

How to send a mail using PHP

Using PHP we can send mail very easily
mailSend mail
mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] );

<?php
$to
= 'test@example.com';$subject = 'Subject';$message = 'Hai this is test description';$headers = 'From: test1@example.com' . "\r\n" .
'Reply-To: test2@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);?>




What is global refference in php

$GLOBALSReferences all variables available in global scope

<?phpfunction test() {
$foo = "local variable";

echo
'$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo
'$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";test();?>


$foo in global scope: Example content
$foo in current scope: local variable  
 

Register Global Varibles In PHP

The following list are the Global Variables.

  1. $_GET
  2. $_POST
  3. $_REQUEST
  4. $_SESSION
  5. $_COOKIE
  6. $_ENV
  7. $_SERVET
  8. $_FILES

Creating modules in drupal7.x

Module  Name

The first step in creating a module is to choose a "short name" for it. This short name will be used in all file and function names in your module, so it must start with a letter, and it must contain only lower-case letters and underscores. For this example, we'll choose "current_posts" as the short name.

Create a folder and a module file

Given that our choice of short name is "current_posts" :
  1. Start the module by creating a folder in your Drupal installation at the path:
    • sites/all/modules/current_posts
  2. Create the PHP file for the module :
    • Save it as current_posts.module in the directory sites/all/modules/current_posts
    • As of Drupal 6.x, sites/all/modules is the preferred place for non-core modules (and sites/all/themes for non-core themes), because this places all site-specific files in the sites directory. This allows you to more easily update the core files and modules without erasing your customizations. Alternatively, if you have a multi-site Drupal installation and this module is for only one specific site, you can put it in sites/your-site-folder/modules.
  3. Add an opening PHP tag to the module :
    • <?php
    • Module files begin with the opening PHP tag. Do not place the CVS ID tag in your module. It is no longer needed with drupal.org's conversion to Git. If the coder module gives you error messages about it, then that module has not yet been updated to drupal.org's Git conventions.
  

File Upload Error Messages Explained

The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['file']['error']

UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION
Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo may help. Introduced in PHP 5.2.0.

Thursday, March 29, 2012

How to determine whether a computer is running a 32-bit version or 64-bit ?

How to find system is working with 32-bit or 64-bit

Find the below steps

Start RUN command line

Start-> Run -> winmsd.exe

Under "System Summary"/ System Type you can find the OS version 

X64 -> 64 Bit
X86 -> 32 Bit

Wednesday, March 28, 2012

Google map Integration?



How to integrate google map integrate into your site.

It's very simple

Find the below code just copy and paste into your application

<!--<div style="width: 600px">
    <iframe width="600" height="300" src="http://regiohelden.de/google-maps/map_en.php?width=600&amp;height=300&amp;hl=en&amp;q=ProWorks%20Contracting%20%2013704%20lrving%20Ave%20S%20%20Burnsville%2C%20MN%2055337+(ProWorks%20Contracting)&amp;ie=UTF8&amp;t=&amp;z=14&amp;iwloc=A&amp;output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0">
    <a href="http://www.regiohelden.de/google-maps/">Google Maps Script</a> von <a href="http://www.regiohelden.de/">RegioHelden</a></iframe><br />
    <span style="font-size: 9px;">
    <a href="http://www.regiohelden.de/google-maps/" style="font-size: 9px;">Google Maps Script</a> by <a href="http://www.regiohelden.de/" style="font-size: 9px;">RegioHelden</a>
    </span>
</div>-->

Saturday, March 24, 2012

Abstracts and Interfaces, what's the difference?

Abstract Class Interfaces

Classes defined as abstract may not be instantiated, and 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. For interface all the methods by default are abstract methods only. So one cannot declare variables or concrete methods in interfaces

In Abstract class we can declare public, private, protected methods & properties In interface class we can declare only public

Abstract class contain abstract methods and common methods Interface class all the methods should be an abstract

A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class. A class can implement many interfaces and Multiple interface inheritance is possible.

Thursday, March 22, 2012

Uses of drupla CMS

The following list shows the most common uses for drupla CMS
  1. Social networking sites
  2. Music & Multimedia web sites
  3. Education
  4. Corporate websites
  5. News and Publishing
  6. Community Portal

To change the XAMPP server port number:


  1. Stop the XAMPP server, if it is running already.
  2. Open the file [XAMPP Installation Folder]/apache/conf/httpd.conf.
  3. Now search for the string Listen 80 (I’m assuming that your XAMPP was using the port 80. Otherwise, just search for the string “Listen”). This is the port number which XAMPP uses. Change this 80 to any other number which you prefer.
  4. Then search for the string “ServerName” and update the port number there also.
  5. Now save and re-start XAMPP server and you are done.

Remove Duplicate Rows from mysql table

How to delete duplicate rows from MySQL table 

It's very simple

In my case as per the requirement admin can import csv file and all the data we need to store in MySQL database

Before inserting data i need to check the data already existed or not ? :)

Find the below code

            $query="SELECT * FROM table";
            $result=mysql_query($query);
            echo mysql_error();
            while($row = mysql_fetch_array($result)){
                $query1="SELECT * FROM table WHERE order_number='".$result_data[0]."' ";
                $result1=mysql_query($query1);
                $count = mysql_num_rows($result1) - 1;
                mysql_query("DELETE FROM table WHERE order_number='".$result_data[0]."' ");
                //echo "deleted $row[1] ";
            }
After this code INSERT the records


Wednesday, March 21, 2012

PHP Security tips

Any web application security is most important throughout the development. There are very simple ways you can take to protect your application from hackers. This post will cover some of the basics of PHP security.

The below mentioned tips every developer should know

1. Filtering Input :-

Filtering all data from external sources is probably the most important security measure you can take. This can be as easy as running some simple built-in functions on your variables.

whenever user enter some data into the form never directly use anything in $_GET or $_POST.. Check each value to make sure it is something expected and assign it to a local variable for use

// input filter examples
 
// Make sure it is an integer
$int = intval($_POST['variable']);
 
// Make it safe to use in a URL
$string = urlencode($_POST['variable']);
 
PHP as of version 5.2 provides a set of filtering functions designed 
just for the purpose of filtering user data. 

filter_input Gets a specific external variable by name and optionally filters it

<?php
$search_html 
filter_input(INPUT_GET'search'FILTER_SANITIZE_SPECIAL_CHARS);$search_url filter_input(INPUT_GET'search'FILTER_SANITIZE_ENCODED);
echo 
"You have searched for $search_html.\n";
echo 
"<a href='?search=$search_url'>Search again.</a>";?>

Out Put

You have searched for Me &#38; son. <a href='?search=Me%20%26%20son'>Search again.</a>  

2.Register_Globals:-

PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0.
This post will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

<?php// define $authorized = true only if user is authenticatedif (authenticated_user()) {
    
$authorized true;
}
// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include 
"/highly/sensitive/data.php";
}
?> 

Example use of sessions with register_globals on or off

<?php// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo 
"Hello <b>{$_SESSION['username']}</b>";

} else {

    echo 
"Hello <b>Guest</b><br />";
    echo 
"Would you like to login?";

}
?>
  

3. Error Reporting:-

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. If the optional level is not set, error_reporting() will just return the current error reporting level.

It's never a good idea to show the world your errors. It make you look bad, it also might give malicious users another clue to help them break your site. You should always have display_errors disabled in a production environment, but continue logging errors with log_errors for your own information.

                Production        Development
display_errors     0                  1
log_errors         1                  0
error_reporting    E_ALL             E_ALL    

4. Use POST for Dangerous Actions

There are two common methods used to send data to a PHP application, GET and POST. GET works by adding variables to the end of URL's (eg. http://www.example.com/process.php?action=delete&id=123). POST works by sending variables in the body of the request (normal users will not see them). It is important to carefully consider which method to use for a certain task.
You should generally stick to POST when you are performing a potentially dangerous action (like deleting something). The reason is that is is much easier to trick a user into accessing a URL with GET parameters than it is to trick them into sending a POST request. Take this example:
<img src="http://www.example.com/process.php?action=delete&id=123" />
If a user with an active session on your site visits another web page with the above image tag, the user's browser will quietly send a request to your site telling it to delete record 123.
Keep in mind that other precautions should also be taken to ensure requests are legitimate under a secure session. It is also easily possible to create a form that does the same as above using a POST request, so don't assume that method is "safe" either. See sections 2 and 4 of the PHP Security Guide for more information on form and session security.

5. Database Queries Filtering:-

Example #1 Simple mysql_real_escape_string() example
<?php// We didn't check $_POST['password'], it could be anything the user wanted! For example:$_POST['username'] = 'aidan';$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users$query "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";mysql_query($query);
// This means the query sent to MySQL would be:echo $query;?>

6.Output Filtering

It is also important to filter what comes out of your applications.
htmlspecialchars();//Convert special characters to HTML entities
htmlspecialchars();//Convert all applicable characters to HTML entities
strip_tags();// Strip HTML and PHP tags from a string

<?php
$new 
htmlspecialchars("<a href='test'>Test</a>"ENT_QUOTES);
echo 
$new// &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;?>

htmlspecialchars();
<?php
$str 
"A 'quote' is <b>bold</b>";
// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;echo htmlentities($str);

 strip_tags():
<?php
$text 
'<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo 
strip_tags($text);
echo 
"\n";
// Allow <p> and <a>echo strip_tags($text'<p><a>');?>