Retrieve coupon details from coupon code WooCommerce

In order for the WC_Coupon function to work, I needed to add the "new" keyword prior to calling the function. As demonstrated below.
$coupon_code = 'save10percent';
global $woocommerce;
$c = new WC_Coupon($coupon_code);
Now I can get details about the coupon like so
 echo "Discount Amount ".$c->amount;//Get Discount amount
echo "Discount Type ".$c->discount_type;//Get type of discount
echo "Individual Use ".$c->individual_use;//Get individual use status
echo "Usage Count ".$c->usage_count;//Get number of times the coupon has been used
echo "Uage Limit ".$c->usage_limit;//Get usage limit
echo "Coupon Description ".$c->description;//Get coupon description

Search only post type in wordpress

By default wordpress search provides a searching function on whole site whether it is pages or post type. In order to make the search only post type in wordpress, below is the code you need to copy and paste it in to your function.php file.

 function filter_search($query) {
if ($query->is_search) {
  $query->set('post_type', array('post','page'));
};
return $query;
};
add_filter('pre_get_posts', 'filter_search');
?>
Notice the line that says
 $query->set('post_type',array('post','page'));
We can filter the search results by changing the values in the array variable. Right now it is set to display posts and pages but you can modify it to display anything we required.

Create a coupon programatically in WooCommerce

We will need to add this code to our child theme’s functions.php file or via a plugin that allows custom functions to be added. We always have to remember, we don’t have to add custom code directly to our parent theme’s functions.php file as this will be wiped entirely when we update the theme.

/**
 * Create a coupon programatically
 */
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
     
$coupon = array(
 'post_title' => $coupon_code,
 'post_content' => '',
 'post_status' => 'publish',
 'post_author' => 1,
 'post_type'  => 'shop_coupon'
);
     
$new_coupon_id = wp_insert_post( $coupon );
     
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

WooCommerce Account Page Custom Endpoint

We can do it using below simple steps. We have to add the below code given in steps in our theme functions.php or in plugin code.

Step 1: In this post, we will see how we can add custom endpoint to my account page in front means one new our own page like order, download (default one’s). To do this, first we’ll add rewrite endpoint using WordPress function ‘add_rewrite_endpoint’ on ‘init’ hook.

function aft_custom_endpoint() {
  add_rewrite_endpoint( 'custom', EP_ROOT | EP_PAGES );
}
 
add_action( 'init', 'aft_custom_endpoint' );

Step 2: Now, we will add menu item for this custom endpoint on WooCommerce My Account page menu so that we can access easily. For this we’ll use ‘woocommerce_account_menu_items’ filter.

add_filter( 'woocommerce_account_menu_items', 'aft_new_menu_items' );
 
/**
* Insert the new endpoint into the My Account menu.
*
* @param array $items
* @return array
*/
function aft_new_menu_items( $items ) {
    $items[ 'custom' ] = __( 'Custom', 'webkul' );
    return $items;
}

The above code will add one more menu item named Custom at the end of my account page menu list.

Step 3: The endpoint has been added, menu item also added, now next thing will be, how can we add content to this new (say) page..? Not to worry, WooCommerce provide the hook using which we can add content –

$endpoint = 'custom';
 
add_action( 'woocommerce_account_' . $endpoint .  '_endpoint', 'aft_endpoint_content' );
 
function aft_endpoint_content() {
    //content goes here
    echo '//content goes here';    
}

How To Change the Author URL Slug in wordpress


Are you looking for a way to change the author URL slug? This snippet will change the default slug, mysite.com/author/name, to mysite.com/profile/name. However, you can change this to anything that you would like.
Instructions:
  1. Add this code to your theme’s functions.php file or in site-specific plugin.
  2. Change profile in line 4 to any name you would like.
add_action('init', 'cng_author_base');
function cng_author_base() {
    global $wp_rewrite;
    $author_slug = 'profile'; // change slug name
    $wp_rewrite->author_base = $author_slug;
}
Note: If changes is not reflecting after adding the code, you can check after updating permalink setting from back-end.

How to check custom fields exists or not

Add a custom field

Now lets just add a custom fields value to our post. After checking the custom fields checkbox, scroll down to the page to see the Custom Fields box. Write your first custom fields name under the Name. It will be a kind of variable to call in our template file. After that write a value you want to display in your post. It should be done under the Value tab.

Get custom fields value to our post

To get the custom fields value we do not need to add any function into the function.php file. Its quite easy to get it by the simple wordperss function.
Just copy the below code into your theme or where you want to display the value.

echo get_post_meta($post->ID, 'Your Custom Fields Name', true);

Check if the custom fields exists or not

With the help of of some if else conditional statement we can check weather the our custom fields name has a value or not.

$key = 'sub-heading';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') { 
 echo '

'.get_post_meta($post->ID, 'sub-heading', true).'

'; }

Adding CC and BCC contact form 7

CC and BCC are emails general header object in which CC means to be Carbon Copy and BCC means Blind Carbon Copy. CC consists of a email id. Adding CC and Bcc contact form 7 is very easy.

CC: example@xyz.com

When an email is composed to send to your client and you want the same email to be sent to you secondary email ID at the same time CC is used. BCC is like CC but it hide the email id of secondary.

One of very popular plugin called contact form 7 has an admin interface that allows you to manage your contact form via admin. It is necessary to know how to add CC and BCC to your contact form 7 via admin panel. You can follow these below steps to accomplished this easy task.

  • Login to your Dashboard
  • Find contact tab on the left panel
  • Click on specific contact form from the form listing.
  • Now click on Mail tab and go to Additional Headers section.
  • Now add your cc email id by following the format ( CC: your-email-id@hosting.com)
  • Scroll down to click on save

HTML5 default validation for confirm password

In this section, we am going to see how you we easily validating HTML5 default validation for confirm the password. Generally in HTML5 when we create a form we simply write “required” attribute to the form element and it starts validating itself without other javascript code. But for confirm password validation we would required to add few lines of code that will set the validation in the default way.

HTML

Confirm password with HTML5

JAVASCRIPT

var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");

function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

Wordpress Update User's Password with PHP

It worked for me to update 'user_pass' using both update_user_meta and wp_update_user:


update_user_meta($user_id, 'user_pass', $newpassword);
wp_update_user( array ('ID' => $user_id, 'user_pass' => $newpassword) ) ;

Get first letter of each word for a given string in PHP

QUESTION:How would I get the first letter of each word for a given string?

$string = "This Is The TEST String";
$result = "TITTS";

ANSWER: explode() on the spaces, then you use the [] notation to access the resultant strings as arrays:

$words = explode(" ", "This Is The TEST String");
$acronym = "";

foreach ($words as $w) {
  $acronym .= $w[0];
}

If you have an expectation that multiple spaces may separate words, switch instead to preg_split()

$words = preg_split("/\s+/", "This Is The TEST String");

Or if characters other than whitespace delimit words (-,_) for example, use preg_split() as well:

// Delimit by multiple spaces, hyphen, underscore, comma
$words = preg_split("/[\s,_-]+/", "This Is The TEST String");

How to Allow Only One Checkbox to be Checked using jQuery

Generally, we use radio buttons to let a user select ONE option from a limited number of choices. Most of the cases radio buttons are ideal to select a single option from a group of the options. But sometimes you required to use the checkbox to do the same functionality like a radio button. If you want to allow the user to check only one checkbox from a group of the checkboxes, it can be done easily using jQuery.
How to Allow Only One Checkbox to be Checked using jQuery
At first, include the jQuery library.

Use the following code to allow only one checkbox to be checked using jQuery.

HTML

 Male
 Female
 Other

JavaScript

$(document).ready(function(){
    $('input:checkbox').click(function() {
        $('input:checkbox').not(this).prop('checked', false);
    });
});

Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page

Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page
Question :
Want to show the css and javascript only when the shortcode is used in that page. If the short code not present in the wordpress page then the js and css of contact form should not be shown.
Solution code for : Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page
Here is the answer for your question. If there is not shortcode the css and js of contact form will be removed and if there is shortcode css and js will be added.
function aft_lwp_contactform_css_js() {
    global $post;
    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'contact-form-7') ) {
        wp_enqueue_script('contact-form-7');
         wp_enqueue_style('contact-form-7');

    }else{
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
    }
}
add_action( 'wp_enqueue_scripts', 'aft_lwp_contactform_css_js');

Fetch contact-form-7 id to another plugin

Fetch contact-form-7 id to another plugin
Question :
How to fetch contact-form-7 forms ID, to another plugin?
I want to get forms id and using that id, I will give some effect to that form, please tell me how to fetch form id from contact-form-7, to another plugin in wordpress.
Solution code for : Fetch contact-form-7 id to another plugin
Actually in contact form 7,the post type is wpcf7_contact_form So you can use this bellow code . In tis code the function return an array of all contact form's id.
function get_cf7_IDS(){
   $cf7_id_array =array();
    if ( post_type_exists( 'wpcf7_contact_form' ) ) {
      $args = array(
        'post_type' => 'wpcf7_contact_form',
        'posts_per_page'=>-1,
      );
      $the_query = new WP_Query( $args );
      if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
          $the_query->the_post();
          $cf7_id_array[]= get_the_ID(); 
        }
        wp_reset_postdata();
      }   
  }
  return $cf7_id_array; //RETURN THE ARRAY OF IDS
}
Then use this function to get all ides in array get_cf7_IDS(). Then let me know the result.

How to hook into Contact Form 7 Before Send

Question :
Solution code for : How to hook into Contact Form 7 Before Send

How to hook into Contact Form 7 Before Send

I had to do this to prevent Email from being sent. Hope it helps.
/*
    Prevent the email sending step for specific form
*/
add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");  
function wpcf7_do_something_else($cf7) {
    // get the contact form object
    $wpcf = WPCF7_ContactForm::get_current();

    // if you wanna check the ID of the Form $wpcf->id

    if (/*Perform check here*/) {
        // If you want to skip mailing the data, you can do it...  
        $wpcf->skip_mail = true;    
    }

    return $wpcf;
}

Contact Form 7 AJAX Callback

Question :
Been searching around on this for a while and can't come up with any documentation to outline what i want to achieve.
I'm using wordpress and the Contact Form 7 plugin, all is working perfectly, what i want to achieve is to run some particular javascript upon form submit, I know we can use "on_sent_ok:" in the additional settings, but this only performs if the form is actually submitted.
What I'd like to do is to do some other javascript when the form doesn't submit ok, which throws the user back to the section which didn't validate.
Contact Form 7 AJAX Callback
Solution code for : Contact Form 7 AJAX Callback
Given the variety of responses on this topic the plugin developer seems to change their mind about how this should work every 5 minutes.
document.addEventListener( 'wpcf7mailsent', function( event ) {
  alert( "Fire!" );
}, false );
And the valid events are:
  • wpcf7invalid — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because there are fields with invalid input.
  • wpcf7spam — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because a possible spam activity has been detected.
  • wpcf7mailsent — Fires when an Ajax form submission has completed successfully, and mail has been sent.
  • wpcf7mailfailed — Fires when an Ajax form submission has completed successfully, but it has failed in sending mail.
  • wpcf7submit — Fires when an Ajax form submission has completed successfully, regardless of other incidents.
Reference: https://contactform7.com/dom-events/

Redirect contact form 7 with javascript

Question :
I do not want to use the additional setting because its filled with a bunch of analytics code. I want to my javascript function to fire when the button is clicked. example the contact form 7's button ID is #aft_submit.
Redirect contact form 7 with javascript
Soution code for : Redirect contact form 7 with javascript
Seen as you are using jquery anyway, you can add the click on the submit button like this
jQuery( document ).ready(function() {
    jQuery("#aft_submit").on('click', function(e){
        e.preventDefault();
        window.location.href  = "http://url-to-redirect.com";
    });
}
You'll need to prevent the default 'submit' action

Wordpress Contact form 7 custom shortcodes

Question :
Contact form 7 has some shortcodes, like [_date] to get todays date. But I want to display the date one week from now.
So I need to create a custom shortcode to Contact form 7 that takes say [next_week] and in the received email the correct date is displayed.
Where and how do I create custom shortcodes to Contact form 7?
Solution code for : Wordpress Contact form 7 custom shortcodes
Adding the following to your functions.php
wpcf7_add_shortcode('custom_date', 'wpcf7_custom_date_shortcode_handler', true);

function wpcf7_custom_date_shortcode_handler($tag) {
    if (!is_array($tag)) return '';

    $name = $tag['name'];
    if (empty($name)) return '';

    $next_week = date('Y-m-d', time() + (60*60*24*7)); 
    $html = '';
    return $html;
}
Now in the "Form" field in CF7 GUI type [custom_date next_week]
Now you can use [next_week] in the message body.

Write HTML in PHP

Examples for : Write HTML in PHP

With print command , you can output HTML code inside php.

Sample code :

print("This is point to print.");

To use quotes inside print command , use \" inside code.

print("Visit Google");

With echo , html output can be done inside php.

echo "

This is HTML code inside echo syntax inside php

";

WooCommerce: Easily Get Product Info (ID, SKU, $) from $product Object

I have been wanting to publish this guide for a long while. As a freelancer, every day I repeat many operations that make me waste time – and one of them is indeed "How to get ___ if we have the $product variable/object?".
For example, "How can we get the product SKU?? Or "How can we get the product short description"? Or maybe the product stock level, shipping class, tax class, price, regular price, sale price, and so on.. Hopefully this article will save you time
Get Product Info

1. If we have access to $product

// Get Product ID
 
$product->get_id(); (fixes the error: "Notice: id was called incorrectly. Product properties should not be accessed directly")
 
// Get Product General Info
 
$product->get_type();
$product->get_name();
$product->get_slug();
$product->get_date_created();
$product->get_date_modified();
$product->get_status();
$product->get_featured();
$product->get_catalog_visibility();
$product->get_description();
$product->get_short_description();
$product->get_sku();
$product->get_menu_order();
$product->get_virtual();
get_permalink( $product->get_id() );
 
// Get Product Prices
 
$product->get_price();
$product->get_regular_price();
$product->get_sale_price();
$product->get_date_on_sale_from();
$product->get_date_on_sale_to();
$product->get_total_sales();
 
// Get Product Tax, Shipping & Stock
 
$product->get_tax_status();
$product->get_tax_class();
$product->get_manage_stock();
$product->get_stock_quantity();
$product->get_stock_status();
$product->get_backorders();
$product->get_sold_individually();
$product->get_purchase_note();
$product->get_shipping_class_id();
 
// Get Product Dimensions
 
$product->get_weight();
$product->get_length();
$product->get_width();
$product->get_height();
$product->get_dimensions();
 
// Get Linked Products
 
$product->get_upsell_ids();
$product->get_cross_sell_ids();
$product->get_parent_id();
 
// Get Product Variations
 
$product->get_attributes();
$product->get_default_attributes();
 
// Get Product Taxonomies
 
$product->get_categories();
$product->get_category_ids();
$product->get_tag_ids();
 
// Get Product Downloads
 
$product->get_downloads();
$product->get_download_expiry();
$product->get_downloadable();
$product->get_download_limit();
 
// Get Product Images
 
$product->get_image_id();
get_the_post_thumbnail_url( $product->get_id(), 'full' );
$product->get_gallery_image_ids();
 
// Get Product Reviews
 
$product->get_reviews_allowed();
$product->get_rating_counts();
$product->get_average_rating();
$product->get_review_count();
 
// source: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

2. If we have access to $product_id

If we have access to the product ID (once again, usually the do_action or apply_filters will make this possible to we), we have to get the product object first. Then, do the exact same things as above.
// Get $product object from product ID
 
$product = wc_get_product( $product_id );
 
// Now you have access to (see above)...
 
$product->get_type();
$product->get_name();
// etc.
// etc.

3. if we have access to the Order object or Order ID

How to get the product information inside the Order? In this case you will need to loop through all the items present in the order, and then apply the rules above.
// Get $product object from $order / $order_id
 
$order = new WC_Order( $order_id );
$items = $order->get_items();
 
foreach ( $items as $item ) {
 
    $product = wc_get_product( $item['product_id'] );
 
    // Now you have access to (see above)...
 
    $product->get_type();
    $product->get_name();
    // etc.
    // etc.
 
}

4. You have access to the Cart object

How to get the product information inside the Cart? In this case, once again, you will need to loop through all the items present in the cart, and then apply the rules above.
// Get $product object from Cart object
 
$cart = WC()->cart->get_cart();
 
foreach( $cart as $cart_item ){
 
    $product = wc_get_product( $cart_item['product_id'] );
 
    // Now you have access to (see above)...
 
    $product->get_type();
    $product->get_name();
    // etc.
    // etc.
 
}

Show original image rather than thumbnail for product on shop page in woocommerce

Solution for : Show original image rather than thumbnail for product on shop page in woocommerce

//show full image on wocommerece list items
remove_action('woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
add_action('woocommerce_before_shop_loop_item_title', 'new_woocommerce_template_loop_product_thumbnail', 10);

function new_woocommerce_template_loop_product_thumbnail() {
 $imgurl= wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
 echo '';
}

Woocommerce get category image full size

Solution for : Woocommerce get category image full size
We can use this wp_get_attachment_image_src function to achieve the goal.
$prod_categories = get_terms( 'product_cat', array(
        'orderby'    => 'name',
        'order'      => 'ASC',
        'hide_empty' => true
    ));

    foreach( $prod_categories as $prod_cat ) :
        $cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
        $shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, 'full' );
        $term_link = get_term_link( $prod_cat, 'product_cat' );?>

         echo '
'; echo $prod_cat->name; echo '----'; echo ''; echo '
'; endforeach; wp_reset_query();

Exclude multiple terms using get_terms() function

Soution for : exclude multiple terms using get_terms() function

With get_terms(), the exclude parameter takes an array of term IDs, so just add the second term to the array:

$terms = get_terms( 'product_cat', array(
    'orderby'    => 'name',
    'order'      => 'ASC',
    'hide_empty' => 0,
    'exclude' => array( 23 ),
    ));

echo '
  • Category:
  • '; foreach ( $terms as $term ) { echo '
  • '.$term->name.'
  • '; }

    WooCommerce Notice Messages, how do I edit them?

    I'm trying to figure out where WooCommerce creates it's messages for when there is a success, error or notice in WooCommerce. I want to edit those messages to fit the scenario more neatly and also edit the HTML. Where are these messages located and how do I edit them?

    Solution code for : WooCommerce Notice Messages, how do I edit them?

    Many of them are directly in the plugin files - unfortunately. Some messages are tied to filter hooks that allow you to edit them without messing with plugin files but that's not always the case.

    The message you wanted to change was "Product Name was successfully added to your cart". This one is set in the function wc_add_to_cart_message in wc-cart-functions.php and this function allows you to change it using a filter:

    wc_add_notice( apply_filters( 'wc_add_to_cart_message', $message, $product_id ) );
    

    So in your functions.php file you could add something like:

    add_filter('wc_add_to_cart_message', 'handler_function_name', 10, 2);
    function handler_function_name($message, $product_id) {
        return "Thank you for adding product" . $product_id;
    }
    

    Setting variable in header.php but not seen in footer.php

    In wordpress , I set a variable in header.php
    $var= 'anything';
    
    but in footer.php when I echo it
    echo $var;
    
    I got no thing printed. why?
    Solution for : setting variable in header.php but not seen in footer.php

    You're not in the same scope, as the header and footer files are included in a function's body. So you are declaring a local variable, and referring to another local variable (from another function).

    So just declare your variable as global:
    $GLOBALS[ 'var' ] = '...';
    
    Then you can echo it globally.
    echo $GLOBALS[ 'var' ];
    

    How To Create Custom User Role in Wordpress

    Soution code for : How To Create Custom User Role in Wordpress

    You can use add role function like

    add_role( $role, $display_name, $capabilities );
    

    Example

    add_role('basic_contributor', 'Basic Contributor', array(
        'read' => true, // True allows that capability
        'edit_posts' => true,
        'delete_posts' => false, // Use false to explicitly deny
    ));
    

    Add a custom class name to Wordpress body tag

    Soution code for : Add a custom class name to Wordpress body tag

    We can use the body_class filter, like so:

    function my_plugin_body_class($classes) {
        $classes[] = 'foo';
        return $classes;
    }
    
    add_filter('body_class', 'my_plugin_body_class');
    

    Although, obviously, our theme needs to call the corresponding body_class function.

    How to horizontally center a <div> using CSS?

    How can we horizontally center a <div> within another <div> using CSS?

    Foo foo

    Solution code for : How to horizontally center a <div> using CSS?

    We can apply this CSS to the inner <div>:

    HTML

    Foo foo

    CSS

    #inner {
      width: 50%;
      margin: 0 auto;
    }
    

    Of course, we don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

    If we are targeting IE8+, it might be better to have this instead:

    HTML

    Foo foo

    CSS

    #inner {
      display: table;
      margin: 0 auto;
    }
    

    It will make the inner element center horizontally and it works without setting a specific width.

    CSS Floating Menu

    Creating a floating menu is very simple and quite easy. The operative code is position:fixed .

    Example of a Floating Menu

    The menu below an example of a floating menu. As we scroll down the page, we will notice the menu stays fixed in the same position on the page.

    HTML

    
     

    Scroll down and watch the menu remain fixed in the same position, as though it was floating.

    CSS

     
      .floating-menu {
        font-family: sans-serif;
        background: yellowgreen;
        padding: 5px;;
        width: 130px;
        z-index: 100;
        position: fixed;
        bottom: 0px;
        right: 0px;
      }
    
      .floating-menu a, 
      .floating-menu h3 {
        font-size: 0.9em;
        display: block;
        margin: 0 0.5em;
        color: white;
      } 
    
    

    We can use the top, bottom, left, and/or right to position the menu exactly where we want it on the page.

    WP_query using meta_query for an ACF checkbox field

    Problem : WP_query using meta_query for an ACF checkbox field

    I’m using WP_Query to show a list of results. I want to filter these based on an ACF checkbox field. I think that I’m getting muddled up with how to correctly parse the ‘value’ array from my ACF field.

    Below solution helped me.

    Soution code for : WP_query using meta_query for an ACF checkbox field

    // Get the selected options
    $my_acf_checkbox_field_arr = get_field('my_checkbox'); // OR  $my_acf_checkbox_field_arr =array('checkbox-value1','checkbox-value2');
    
    // Build the meta query based on the selected options
    $meta_query = array('relation' => 'OR');
    foreach( $my_acf_checkbox_field_arr as $item ){
        $meta_query[] = array(
            'key'     => 'checkbox',
            'value'   => $item,
            'compare' => 'LIKE',
        );
    }
    
    // args
    $args = array(
     'numberposts' => -1,
     'post_type'  => 'my-cpt',
     'meta_query' => $meta_query,
    );
    
    $the_query = new WP_Query( $args );
    

    Wordpress session variable not working

    Problem : Wordpress session variable not working

    I have an issue with a WordPress session.

    In the file themes/theme-name/header.php I wrote this code:

    session_start();
    
    if(isset($_SESSION['var'])) {
          echo 'Welcome'; 
    }  else if(isset($_POST['var'])) {
           $_SESSION['var'] = $_POST['var']; 
    } else {
           echo 'No access...';
           exit; 
    }
    

    Solution For : Wordpress session variable not working

    Just hook a function on "init" in your functions.php like this :

    function ur_theme_start_session()
    {
        if (!session_id())
            session_start();
    }
    add_action("init", "ur_theme_start_session", 1);
    

    Then we can use our session variables.

    I hope that help you.

    How to include pagination in a Wordpress Custom Post Type Query

    Solution for : How to include pagination in a Wordpress Custom Post Type Query

    If we have to get the list for custom post type "project". Below is simple code to achieve our goal.

    $the_query = new WP_Query( 
     array('posts_per_page'=>20,
     'post_type'=>'project',
     'paged' => get_query_var('paged') ? get_query_var('paged') : 1) 
     );
     
     
    while ($the_query -> have_posts()) : $the_query -> the_post();
    
    echo '';
    endwhile; 
     
    $big = 999999999; // need an unlikely integer
    echo paginate_links( array(
        'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $the_query->max_num_pages
    ) );
    
    wp_reset_postdata();
    

    Get cart item name, quantity all details woocommerce

    Solution for : Get cart item name, quantity all details woocommerce.

    I am trying to send the woocommerce cart items to third party shipping tool. I need the item name, quantity and individual price to be sent to the third party. How can this be achieved?

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    
    foreach($items as $item => $values) { 
     $_product =  wc_get_product( $values['data']->get_id()); 
     echo "".$_product->get_title().'  
    Quantity: '.$values['quantity'].'
    '; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."
    "; }

    To get Product Image and Regular & Sale Price:

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    
    foreach($items as $item => $values) { 
     $_product =  wc_get_product( $values['data']->get_id() );
     //product image
     $getProductDetail = wc_get_product( $values['product_id'] );
     echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )
    
     echo "".$_product->get_title() .'  
    Quantity: '.$values['quantity'].'
    '; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."
    "; /*Regular Price and Sale Price*/ echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."
    "; echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."
    "; }

    WooCommerce - get category for product page

    Solution for : WooCommerce - get category for product page

    A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ($terms as $term) {
        $product_cat_id = $term->term_id;
        break;
    }
    

    Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

    echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
    
    

    How to remove woocommerce tab?

    Solution for : How to remove woocommerce tab?

    While CSS is great, if the stylesheet doesn't load correctly, you could end up showing someone tabs without meaning to. It is best to remove the content before loading (server side), by using a filter, as you had mentioned.

    See code below as provided from Woothemes for unsetting data tabs.
    EDIT Place within the functions.php file inside your theme.

    add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
    
    function woo_remove_product_tabs( $tabs ) {
        unset( $tabs['description'] );          // Remove the description tab
        unset( $tabs['reviews'] );          // Remove the reviews tab
        unset( $tabs['additional_information'] );   // Remove the additional information tab
        return $tabs;
    }
    

    Override WooCommerce Frontend Javascript

    Solution for : Override WooCommerce Frontend Javascript

    I had the same problem except with add-to-cart.js. Simple solution is to DEQUEUE the woocommerce script and ENQUEUE your replacement. In my case I added the following to my functions.php:

    wp_dequeue_script('wc-add-to-cart');
    wp_enqueue_script( 'wc-add-to-cart', get_bloginfo( 'stylesheet_directory' ). '/js/add-to-cart-multi.js' , array( 'jquery' ), false, true );
    

    You would want to DEQUEUE the 'wc-add-to-cart-variation' script. I don't think you have to ENQUEUE with the same name, but I couldn't see a reason not to.

    Hope this helps.

    If you're using WordPress Version 4.0.1 and WooCommerce Version 2.2.10. You can use the following scripts:

    wp_deregister_script('wc-add-to-cart');
    wp_register_script('wc-add-to-cart', get_bloginfo( 'stylesheet_directory' ). '/js/add-to-cart-multi.js' , array( 'jquery' ), WC_VERSION, TRUE);
    wp_enqueue_script('wc-add-to-cart');
    

    Short Description in checkout woocommerce wordpress

    Solution for : How do you add a short description for each product to the checkout page in Woocommerce?

    The filter woocommerce_get_item_data can be used for that.

    Like so:

    add_filter( 'woocommerce_get_item_data', 'wc_checkout_description_so_15127954', 10, 2 );
    
    function wc_checkout_description_so_15127954( $other_data, $cart_item )
    {
        $post_data = get_post( $cart_item['product_id'] );
        $other_data[] = array( 'name' =>  $post_data->post_excerpt );
        return $other_data;
    }
    

    Note that maybe some kind of checking will be needed, e.g., make sure this filter is only called when actually viewing the Checkout page, as I don't know if it'll be called in other instances.

    Woocommerce - Get SKU in product single page

    Solution for : To get SKU in product single page in woocommerce

    Below is code/function To get SKU in product single page in woocommerce

    get_sku() is a method of the WC_Product class, so you need to have a product on which to call it, like this:

    echo $product->get_sku();
    

    This should work if you are inside the WooCommerce product loop, and is what is used in the WooCommerce template files. If you don't already have a reference to the product object, you may need to add the following line at the top of the file in order to access it:

    global $product;
    

    Get custom attribute in woocommerce

    Solution for : Get custom attribute in woocommerce

    Below is code/function to Get custom attribute in woocommerce.

    If attribute key is "pa_specification"

    function woo_new_product_tab_content() {
        // The new tab content    
        global $post; 
    
        $product_id = $post->ID;
    
        $product = new WC_Product( $product_id );
    
        $pa_value = $product->get_attribute('pa_specification'); 
    
        echo $pa_value; 
    
    }
    

    Woocommerce code get list products

    Solution for : Woocommerce code get list products

    Below code will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement

     $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 10,
            'product_cat'    => 'hoodies'
        );
    
        $loop = new WP_Query( $args );
    
        while ( $loop->have_posts() ) : $loop->the_post();
            global $product;
            echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
        endwhile;
    
        wp_reset_query();
    

    WooCommerce- change admin date format

    Solution for : WooCommerce- change admin date format

    I would like to change the WooCommerce date format from Y/m/d to d/m/Y. I have the Print invoice plug-in, and the dates are in the y/m/d format as taken from the date ordered in WooCommerce.

    You also have to change the value of '$t_time' variable using the same 'post_date_column_time' filter.You have to return two values ($t_time and $h_time) using two separate callback functions. Your code will work when you add following callback on same filter in addition to your code.

    add_filter( 'post_date_column_time' ,'woo_custom_post_date_column_time_withDate' );
    
    function woo_custom_post_date_column_time_withDate( $post ) {  
    $t_time = get_the_time( __( 'd/m/Y g:i:s A', 'woocommerce' ), $post );
     return $t_time; 
    }
    

    Also check the format you have set into the call back function, change it to 'd/m/Y' since you require it.

    Woocommerce replace 'add to cart' button with custom button/ product link

    Solution for : Woocommerce replace add to cart button with custom button/link

    Replacing the button add to cart by a link to the product in Shop and archives pages for woocommerce 3+

    add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
    function replacing_add_to_cart_button( $button, $product  ) {
        $button_text = __("View product", "woocommerce");
        $button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    
        return $button;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested on WooCommerce 3+ and works. You can customize the text of button and you will get something like:

    Removing index.php from a URL path in XAMPP for Windows

    STEP 1: Create .htaccess using the command prompt in Windows

    1. Open command prompt

    2. In the command prompt, change the working directory to the CodeIgniter directory i.e. the directory that contains the application and system directories

      cd C:\xampp\htdocs\site_folder

    3. Type copy con .htaccess to create a .htaccess file in the current working directory

    4. Press [ENTER] to append an empty line

    5. Type the following code:

      <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php/$1 [L]
      </IfModule>
      
    6. Finally, enter CTRL + Z to append the data to the .htaccess file and hit [ENTER] to save

    STEP 2: Configure mod_rewrite in httpd.conf

    1. Locate the httpd.conf file in the Apache sub-directory C:\xampp\apache\conf\httpd.conf

    2. Uncomment the following line from: #LoadModule rewrite_module modules/mod_rewrite.so

      to

      LoadModule rewrite_module modules/mod_rewrite.so

    3. Save the changes to the file

    STEP 3: Configure config.php in you site_folder (CodeIgniter) folder

    1. Locate config.php C:\xampp\htdocs\site_folder\system\application\config

    2. Change the following line from: $config['index_page'] = 'index.php';

      to

      $config['index_page'] = '';

    How to import a product programmatically in magento 2

    Solution for : How to import a product programmatically in Magento 2

    Below is the simple example fo achieve the solution:

    use Magento\Framework\App\Bootstrap;
    
    include("../app/bootstrap.php");
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $state = $objectManager->get('Magento\Framework\App\State');
    $state->setAreaCode('frontend');
    
    $simpleProduct = $objectManager->create('\Magento\Catalog\Model\Product');
    $simpleProduct->setSku('Testing3');
    $simpleProduct->setName('Testing3');
    $simpleProduct->setAttributeSetId(9);
    $simpleProduct->setCategoryIds(3);
    $simpleProduct->setDescription('This is for testing');
    $simpleProduct->setStatus(1);
    $simpleProduct->setTypeId('simple');
    $simpleProduct->setPrice(500);
    $simpleProduct->setWebsiteIds(array(1));
    $simpleProduct->setVisibility(4);
    $simpleProduct->setUrlKey('Testing3');
    
    $simpleProduct->setStockData(array(
        'is_in_stock' => 1, //Stock Availability
        'qty' => 100//qty
            )
    );
    
    $attr = $simpleProduct->getResource()->getAttribute('color');
    $attributeOptionId = $attr->getSource()->getOptionId('Red'); //name in Default Store View
    $simpleProduct->setData('color', $attributeOptionId);
    
    $simpleProduct->save();
    $simpleProductId = $simpleProduct->getId();
    echo "Simple Product ID: " . $simpleProductId . "\n";
    

    How to calculate minute difference between two date-times in PHP?

    Solution for : How to calculate minute difference between two date-times in PHP?

    Below is the simple example fo achieve the solution:

    $to_time = strtotime("2008-12-13 10:42:00");
    $from_time = strtotime("2008-12-13 10:21:00");
    echo round(abs($to_time - $from_time) / 60,2). " minute";
    

    How to read if a checkbox is checked in PHP?

    Solution for :How to read if a checkbox is checked in PHP?

    If our HTML page looks like this:

    
    

    After submitting the form we can check it with:

    isset($_POST['checkbox1'])
    

    OR

    if ($_POST['checkbox1'] == 'value1'){ 
    
    //I am checked.
    
    }
    

    Test if number is odd or even in php

    Solution for : What is the simplest most basic way to find out if a number/variable is odd or even in PHP? Is it something to do with mod?

    You were right in thinking mod was a good place to start. Here is an expression which will return true if $number is even, false if odd:

    $number % 2 == 0
    

    Example:

    $number = 20;
    if ($number % 2 == 0) {
      print "I am even";
    }
    

    Output:

    I am even

    How to find and replace text in a MySQL database

    Solution for : How to find and replace text in a MySQL database

    I have a column containing urls (id, url):

    http://www.example.com/articles/updates/123
    http://www.example.com/articles/updates/345
    http://www.example.com/articles/updates/234
    

    I'd like to change the word "updates" to "events". Is it possible to do this with a script?

    QUERY: We can achieve the above requirements using below query.

    UPDATE your_table
    SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/events/')
    WHERE your_field LIKE '%articles/updates/%'
    

    Find duplicate records in MySQL

    Solution for :I want to pull out duplicate records in a MySQL Database.

    The key is to rewrite this query so that it can be used as a sub-query.

    EXAMPLE QUERY:

    SELECT firstname, 
       lastname, 
       list.address 
    FROM list
       INNER JOIN (SELECT address
                   FROM   list
                   GROUP  BY address
                   HAVING COUNT(id) > 1) dup
               ON list.address = dup.address;
    

    How to find all the tables in MySQL with specific column names in them?

    Solution for :How to find all the tables in MySQL with specific column names in them?

    To get all tables with columns columnA or ColumnB in the database YourDatabase:

    QUERY:

    SELECT DISTINCT TABLE_NAME 
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE COLUMN_NAME IN ('columnA','ColumnB')
            AND TABLE_SCHEMA='YourDatabase';
    

    Insert into a MySQL table or update if exists

    Solution for :Insert into a MySQL table or update if exists

    If I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

    For example:

    insert into table (id, name, age) values(1, "A", 20)
    

    Let’s say the unique key is id, and in my database there is a row with id = 1. In that case I want to update that row with these values. Normally this gives an error. If I use insert IGNORE it will ignore the error, but it still won’t update.

    We can use INSERT ... ON DUPLICATE KEY UPDATE

    QUERY:

    INSERT INTO table (id, name, age) VALUES(1, "A", 20) ON DUPLICATE KEY UPDATE    
    name="A", age=20
    

    How to output MySQL query results in CSV format?

    Solution for :Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?

    SELECT order_id,product_name,qty
    FROM orders
    WHERE foo = 'bar'
    INTO OUTFILE '/var/lib/mysql-files/orders.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n';
    

    Using this command columns names will not be exported.

    Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

    If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

    jQuery Ajax POST example with PHP

    Solution for : jQuery Ajax POST example with PHP

    I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.

    First of all, create two files, for example form.php and process.php.

    We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.

    form.php

    Validate the form using jQuery client-side validation and pass the data to process.php.

    $(document).ready(function() {
        $('form').submit(function(event) { //Trigger on form submit
            $('#name + .throw_error').empty(); //Clear the messages first
            $('#success').empty();
    
            //Validate fields if required using jQuery
    
            var postForm = { //Fetch form data
                'name'     : $('input[name=name]').val() //Store name fields value
            };
    
            $.ajax({ //Process the form using $.ajax()
                type      : 'POST', //Method type
                url       : 'process.php', //Your form processing file URL
                data      : postForm, //Forms name
                dataType  : 'json',
                success   : function(data) {
                                if (!data.success) { //If fails
                                    if (data.errors.name) { //Returned if any error from process.php
                                        $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                    }
                                }
                                else {
                                        $('#success').fadeIn(1000).append('

    ' + data.posted + '

    '); //If successful, than throw a success message } } }); event.preventDefault(); //Prevent the default submit }); });

    Now we will take a look at process.php

    $errors = array(); //To store errors
    $form_data = array(); //Pass back the data to `form.php`
    
    /* Validate the form on the server side */
    if (empty($_POST['name'])) { //Name cannot be empty
        $errors['name'] = 'Name cannot be blank';
    }
    
    if (!empty($errors)) { //If errors in validation
        $form_data['success'] = false;
        $form_data['errors']  = $errors;
    }
    else { //If not, process the form, and return true on success
        $form_data['success'] = true;
        $form_data['posted'] = 'Data Was Posted Successfully';
    }
    
    //Return the data back to form.php
    echo json_encode($form_data);
    
    

    How to calculate the difference between two dates using PHP?

    Solution for : How to calculate the difference between two dates using PHP?

    I suggest to use DateTime and DateInterval objects.

    $date1 = new DateTime("2007-03-24");
    $date2 = new DateTime("2009-06-26");
    $interval = $date1->diff($date2);
    echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 
    
    // shows the total amount of days (not divided into years, months and days like above)
    echo "difference " . $interval->days . " days ";
    

    read more php DateTime::diff manual

    From the manual:

    As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

    $date1 = new DateTime("now");
    $date2 = new DateTime("tomorrow");
    
    var_dump($date1 == $date2); // bool(false)
    var_dump($date1 < $date2);  // bool(true)
    var_dump($date1 > $date2);  // bool(false)
    

    Returning JSON from a PHP Script: A Quick Guide

    JSON (JavaScript Object Notation) has become the standard format for exchanging data between clients and servers. If you're working with PHP, returning JSON from your script is straightforward and incredibly useful for building APIs or handling AJAX requests.

    Why Use JSON?

    • Lightweight and easy to read
    • Natively supported by JavaScript
    • Ideal for client-server communication

    How to Return JSON in PHP

    Here’s a step-by-step guide:

    1. Set the Content-Type Header

    To ensure the response is treated as JSON, use:

    header('Content-Type: application/json');
    

    2. Create Your Data

    Build an associative array or object to hold your data:

    $data = [
        "status" => "success",
        "message" => "Data retrieved successfully",
        "data" => [1, 2, 3, 4]
    ];
    
    

    3. Convert to JSON

    Use json_encode() to convert your PHP data into a JSON string:

    echo json_encode($data);
    
    

    Example Script

    Here’s a complete example:

     "success",
        "message" => "This is your JSON response!",
        "items" => ["item1", "item2", "item3"]
    ];
    
    // Return JSON
    echo json_encode($data);
    ?>
    
    

    Error Handling

    Always check for encoding errors:

     "JSON encoding failed"]);
    }
    
    ?>
    
    

    Testing Your Script

    • Use tools like Postman to test your script.
    • For a quick check, call your PHP script via AJAX or in the browser.

    With this guide, you can start building JSON-based APIs and create seamless client-server integrations. For more tips, check out See Coding Blog!!

    Getting product Image url in Magento 2

    Solution for : Getting product Image url in Magento 2.

    We can get using below simple lines:

     
    $imagehelper = $objectManager->create('Magento\Catalog\Helper\Image');
    $image = $imagehelper->init($_product,'category_page_list')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();
    
    echo '';
    

    Some useful MySQL DATABASE interview questions

    How do you start MySQL on Linux?
    - /etc/init.d/mysql start

    How do you start and stop MySQL on Windows?
    net start MySQL, net stop MySQL
    What’s the default port for MySQL Server?
    3306
     
    What does tee command do in MySQL?
     tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.
     
    Can you save your connection settings to a conf file?
    Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 600, so that it’s not readable by others.
     
    Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks you accomplished with these tools.
     
    What are some good ideas regarding user security in MySQL?
    There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet). There are as few users as possible (in the ideal case only root) who have unrestricted access.
     
    How do you change a password for an existing user via mysqladmin?
    mysqladmin -u root -p password "newpassword"
     
    Explain the difference between MyISAM Static and MyISAM Dynamic.
    In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
     
    What does myisamchk do?
    It compressed the MyISAM tables, which reduces their disk usage.
     
    Explain advantages of InnoDB over MyISAM?
    Row-level locking, transactions, foreign key constraints and crash recovery.
     
    Explain advantages of MyISAM over InnoDB?
    Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
     
    What are HEAP tables in MySQL?
    HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
     
    How do you control the max size of a HEAP table?
    MySQL config variable max_heap_table_size.
     
    Explain the difference between mysql and mysqli interfaces in PHP?
    mysqli is the object-oriented version of mysql library functions.
     
    What are CSV tables?
    Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
     
    Explain federated tables. - Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
     
    What is SERIAL data type in MySQL?
    BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
     
    What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
    It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
     
    Explain the difference between FLOAT, DOUBLE and REAL.
    FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
     
    If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table? - 999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
     
    Use mysqldump to create a copy of the database?
     mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
     
    What happens if a table has one column defined as TIMESTAMP? 
    That field gets the current timestamp whenever the row gets altered.
     
    But what if you really want to store the timestamp data, such as the publication date of the article? Create two columns of type TIMESTAMP and use the second one for your real data.
     
    Explain the difference between BOOL, TINYINT and BIT.
    Prior to MySQL 5.0.3: those are all synonyms. After MySQL 5.0.3: BIT data type can store 8 bytes of data and should be used for binary data.
     

    PHP interview Questions ( basics )

    1. What is PHP?
      PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning

    2. What is the use of "echo" in php?
      It is used to print a data in the webpage, Example:
       echo 'Car insurance';  
      The following code print the text in the webpage

    3. How to include a file to a php page?
      We can include a file using include() " or "require()" function with file path as its parameter.

    4. What's the difference between include and require?
      If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

    5. require_once(), require(), include(). What is difference between them?
      require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

    6. Differences between GET and POST methods ?
      We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .

    7. How to declare an array in php?
      Eg :
       var $arr = array('apple', 'grape', 'lemon');

    8. What is the use of 'print' in php?
      This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list.

      Example
      print('PHP Interview questions');
       print 'Job Interview ');

    9. What is use of in_array() function in php ?
      in_array used to checks if a value exists in an array

    10. What is use of count() function in php ?
      count() is used to count all elements in an array, or something in an object

    11. What’s the difference between include and require?
      It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

    12. What is the difference between Session and Cookie?
      The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking

    13. How to set cookies in PHP?
      Setcookie("sample", "ram", time()+3600);

    14. How to Retrieve a Cookie Value?
      eg :
      echo $_COOKIE["user"];

    15. How to create a session? How to set a value in session ? How to Remove data from a session?
      Create session :
       session_start();
      Set value into session :
      $_SESSION['USER_ID']=1;
      Remove data from a session :
      unset($_SESSION['USER_ID'];

    16. what types of loops exist in php?
      for,while,do while and foreach (NB: You should learn its usage)

    17. How to create a mysql connection?
      mysql_connect(servername,username,password);

    18. How to select a database?
      mysql_select_db($db_name);

    19. How to execute an sql query? How to fetch its result ?
      $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); 
      $result = mysql_fetch_array($my_qry);
      echo $result['First_name'];
      
    20. Write a program using while loop
      $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); 
      while($result = mysql_fetch_array($my_qry))
      {
      echo $result['First_name'.]."<br/>";
      }
      
    21. How we can retrieve the data in the result set of MySQL using PHP?
      • 1. mysql_fetch_row
      • 2. mysql_fetch_array
      • 3. mysql_fetch_object
      • 4. mysql_fetch_assoc 
    22. What is the use of explode() function ?
      Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
      This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.

    23. What is the difference between explode() and split() functions?
      Split function splits string into array by regular expression. Explode splits a string into array by string.

    24. What is the use of mysql_real_escape_string() function?
      It is used to escapes special characters in a string for use in an SQL statement

    25. Write down the code for save an uploaded file in php.
      f ($_FILES["file"]["error"] == 0)
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/" . $_FILES["file"]["name"]);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
      
    26. How to create a text file in php?
      $filename = "/home/user/guest/newfile.txt";
      $file = fopen( $filename, "w" );
      if( $file == false )
      {
      echo ( "Error in opening new file" ); exit();
      }
      fwrite( $file, "This is a simple test\n" );
      fclose( $file );
      
    27. How to strip whitespace (or other characters) from the beginning and end of a string ?
      The trim() function removes whitespaces or other predefined characters from both sides of a string.

    28. What is the use of header() function in php ?
      The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.

    29. How to redirect a page in php?
      The following code can be used for it,
      header("Location:index.php");

       
    30. How stop the execution of a php scrip ?
      exit() function is used to stop the execution of a page

    31. How to set a page as a home page in a php based site ?
      index.php is the default name of the home page in php based sites

    32. How to find the length of a string?
      strlen() function used to find the length of a string

    33. what is the use of rand() in php?
      It is used to generate random numbers.If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

    34. what is the use of isset() in php?
      This function is used to determine if a variable is set and is not NULL

    35. What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?
      mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array() fetches an associative array, a numeric array, or both

    36. What is mean by an associative array?
      Associative arrays are arrays that use string keys is called associative arrays.

    37. What is the importance of "method" attribute in a html form?
      "method" attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the URL.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

    38. What is the importance of "action" attribute in a html form?
      The action attribute determines where to send the form-data in the form submission.

    39. What is the use of "enctype" attribute in a html form?
      The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as "multipart/form-data" when we are using a form for uploading files

    40. How to create an array of a group of items inside an HTML form ?
      We can create input fields with same name for "name" attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP.
      For instance :
       
      
       
      
      
      
    41. Define Object-Oriented Methodology
      Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships

    42. How do you define a constant?
      Using define() directive, like
       define ("MYCONSTANT",150)

    43. How send email using php?
      To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg :
       mail($to,$subject,$message,$headers); 
    44. How to find current date and time?
      The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don't, the current timestamp will be used.

    45. Difference between mysql_connect and mysql_pconnect?
      There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

    46. What is the use of "ksort" in php?
      It is used for sort an array by key in reverse order.

    47. What is the difference between $var and $$var?
      They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var. For example, if $var contains "message", $$var is the same as $message.

    48. What are the encryption techniques in PHP
      MD5 PHP implements the MD5 hash algorithm using the md5 function,
      eg : $encrypted_text = md5 ($msg);
      mcrypt_encrypt :-
       string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ); 
      Encrypts plaintext with given parameters

    49. What is the use of the function htmlentities?
      htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

    50. How to delete a file from the system
      Unlink() deletes the given file from the file system.

    51. How to get the value of current session id?
      session_id() function returns the session id for the current session.

    52. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
      • Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.
      • mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
      • mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
      •  
    53. 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.
    54. what is sql injection ?
      SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications

    55. What is x+ mode in fopen() used for?
      Read/Write. Creates a new file. Returns FALSE and an error if file already exists

    56. How to find the position of the first occurrence of a substring in a string
      strpos() is used to find the position of the first occurrence of a substring in a string

    57. What is PEAR?
      PEAR is a framework and distribution system for reusable PHP components.The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style.PEAR is broken into three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The Core Components include the base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing functions. The PEAR Packages include functionality providing for authentication, networking, and file system features, as well as tools for working with XML and HTML templates.

    58. Distinguish between urlencode and urldecode?
      This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the urldecode->Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function.

    59. What are the different errors in PHP?
      In PHP, there are three types of runtime errors, they are:
      Warnings:
      These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
      Notices:
      These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
      Fatal errors:
      These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.