Monday, September 30, 2013

How To Check if an array is empty in PHP?

You can use PHP inbuilt functions; array_filter() and empty() to check if an array is empty.

array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false. Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.

empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false.

$errors = array_filter($_POST);

if (empty($errors)) {

 echo "array is empty.";
}
else
{
 echo "It is not empty.";
}
Ref: http://stackoverflow.com/a/8329005

Thursday, September 26, 2013

How to Update Keyword Status using Google Adwords API ?

You can pause any active keyword or vice versa using Google Adwords API PHP Client Library. Using following method, you can Enable a 'PAUSED' keyword and Paused a 'ACTIVE' keyword. You can delete the keyword as well.

Three states of keywords are:
ACTIVE : Default state of a criterion (e.g. not paused).
DELETED : Criterion is deleted.
PAUSED : Criterion is paused. Also used to pause a criterion.

Following function can be used to update the keyword status from 'PAUSED' to 'ACTIVE' and 'ACTIVE' to 'PAUSED'.

The key thing is to update the userStatus field.

NOTE: During an ADD and SET operation: It may not be set to DELETED.
/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id of the ad group that contains the keyword
 * @param string $criterionId the id of the keyword
 * @param string $status the status of the keyword
 */
function UpdateKeyword($user, $adGroupId, $criterionId, $status){
 
 // Get the service, which loads the required classes.
  $adGroupCriterionService =
      $user->GetService('AdGroupCriterionService', ADWORDS_VERSION); 
 
   // Create criterion using an existing ID. Use the base class Criterion
  // instead of Keyword to avoid having to set keyword-specific fields.
  $criterion = new Criterion();
  $criterion->id = $criterionId;

  // Create ad group criterion.
  $adGroupCriterion = new BiddableAdGroupCriterion();
  $adGroupCriterion->adGroupId = $adGroupId;
  $adGroupCriterion->criterion = new Criterion($criterionId);
  
   $adGroupCriterion->userStatus = $status;  
 
   // Create operation.
  $operation = new AdGroupCriterionOperation();
  $operation->operand = $adGroupCriterion;
  $operation->operator = 'SET';

  $operations = array($operation);

  // Make the mutate request.
  $result = $adGroupCriterionService->mutate($operations);

  // Display result.
  $adGroupCriterion = $result->value[0];
  return $adGroupCriterion;

}


If you want to delete the keyword use following function. You must use 'REMOVE' operator to delete keyword.
/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id of the ad group that the keyword is in
 * @param string $criterionId the id of the keyword to delete
 */
function DeleteKeyword($user, $adGroupId, $criterionId) {
  // Get the service, which loads the required classes.
  $adGroupCriterionService =
      $user->GetService('AdGroupCriterionService', ADWORDS_VERSION);

  // Create criterion using an existing ID. Use the base class Criterion
  // instead of Keyword to avoid having to set keyword-specific fields.
  $criterion = new Criterion();
  $criterion->id = $criterionId;

  // Create ad group criterion.
  $adGroupCriterion = new AdGroupCriterion();
  $adGroupCriterion->adGroupId = $adGroupId;
  $adGroupCriterion->criterion = new Criterion($criterionId);

  // Create operation.
  $operation = new AdGroupCriterionOperation();
  $operation->operand = $adGroupCriterion;
  $operation->operator = 'REMOVE';

  $operations = array($operation);

  // Make the mutate request.
  $result = $adGroupCriterionService->mutate($operations);

  // Display result.
  $adGroupCriterion = $result->value[0];
  printf("Keyword with ID '%s' was deleted.\n",
      $adGroupCriterion->criterion->id);
}

Reference: Google Adwords API PHP

How to update text ad status using Google Adwords Api and PHP client library?

There are three status of text Ad:
1. ENABLED
2. DISABLED
3. PAUSED

If you delete AdGroupAd using 'REMOVE' operator then you can't change it anymore. If you try to update it back to 'ENABLED/PAUSED' you will get AdGroupAdError -> CANNOT_OPERATE_ON_DELETED_ADGROUPAD (Deleted ads may not be modified).

If you want to delete the AdGroupAd use following function and it uses 'REMOVE' Operator. This means that such Ad can't be changed anymore. It will never be fully deleted, but they will always exist in your account with the status 'DISABLED'.

For example
function DeleteAd($user, $adGroupId, $adId) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create base class ad to avoid setting type specific fields.
  $ad = new Ad();
  $ad->id = $adId;

  // Create ad group ad.
  $adGroupAd = new AdGroupAd();
  $adGroupAd->adGroupId = $adGroupId;
  $adGroupAd->ad = $ad;

  // Create operation.
  $operation = new AdGroupAdOperation();
  $operation->operand = $adGroupAd;
  $operation->operator = 'REMOVE';

  $operations = array($operation);

  // Make the mutate request.
  $result = $adGroupAdService->mutate($operations);

  // Display result.
  $adGroupAd = $result->value[0];
  printf("Ad with ID '%s' was deleted.\n", $adGroupAd->ad->id);
}

If you want to modify a text ad that was created, then you must use 'SET' Operator. You can update the status of text ad using following function together with 'SET' Operator.

Best Practice will be: Instead of setting status to 'DISABLED', you could set it to 'PAUSED'. And if adding of new AdGroupAd doesn't succeed, you could always revert old AdGroupAd from 'PAUSED' to 'ACTIVE'.

For example
/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id of the ad group containing the ad
 * @param string $adId the ID of the ad
 * @param string $status the status(ACTIVE, DELETED, PAUSED) of the ad
 */
function UpdateAd($user, $adGroupId, $adId, $status) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create ad using an existing ID. Use the base class Ad instead of TextAd to
  // avoid having to set ad-specific fields.
  $ad = new Ad();
  $ad->id = $adId;

  // Create ad group ad.
  $adGroupAd = new AdGroupAd();
  $adGroupAd->adGroupId = $adGroupId;
  $adGroupAd->ad = $ad;

 if($status == "DELETED")
  {
  $adGroupAd->status = 'DISABLED'; 
  }
  
  if($status == "ACTIVE")
  {
  $adGroupAd->status = 'ENABLED'; 
  }

  if($status == "PAUSED")
  {
    $adGroupAd->status = 'PAUSED';
  }
  // Create operation.
  $operation = new AdGroupAdOperation();
  $operation->operand = $adGroupAd;   
  $operation->operator = 'SET';   
  $operations = array($operation);

  // Make the mutate request.
  $result = $adGroupAdService->mutate($operations);

  // Display result.
  $adGroupAd = $result->value[0];
  

  printf("Ad of type '%s' with ID '%s' has updated status '%s'.\n",
      $adGroupAd->ad->AdType, $adGroupAd->ad->id, $adGroupAd->status);
}

Source: google-api-adwords-php library v201306

Monday, September 23, 2013

How to strip whitespace from an array using PHP?

You can strip white space from an array by using a combination of following php functions.

  • array_filter — Filters elements of an array using a callback function
  • array_map — Applies the callback to the elements of the given arrays
  • trim — Strip whitespace (or other characters) from the beginning and end of a string

Syntax
array_filter(array_map('trim', $array));
This will remove all whitespace from the sides (but not between chars). And it will remove any entries of input equal to FALSE (e.g. 0, 0.00, null, false, …)

For example
$array = array(' foo ', 'bar ', ' baz', '    ', '', 'foo bar');
$array = array_filter(array_map('trim', $array));
print_r($array);

// Output
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [5] => foo bar
)

Source: http://stackoverflow.com/a/3384083

Thursday, September 19, 2013

When and How To Use Indexes In Mysql ?



This comes up in discussions almost every new project I work on, because it's a very important thing to consider when designing a database. When deciding when and how to create an index in your MySQL database, it's important to consider how the data is being used.

Let's say you have a database of employees. We will create it like this:
CREATE TABLE employees (
ID INT,
name VARCHAR(60),
salary decimal(10,2),
date hired(date)
)

So you will notice that this table is pretty simplistic, and doesn't really contain all the info you would need to actually manage employees, but its just for the sake of demonstration, and you could always add more later, or even make another table and use joins if you had really complex needs.

For now we will go over these real quick.

The ID is basically just a number (INT) which can hold a very large number. If this were real world I would probably make it unsigned, since you will never have a negative employee ID – but either way, you will never reach the number of employees it would take to get to the number that would fill up an INT.

Even unsigned int will hold values up to 2,147,483,647. So if you have 2 billion employees, you would probably not be a developer anymore ;-).

You might want to consider making the field an auto increment, and primary key, the auto increment depending on how data will be entered into this database.

Name is a simple varchar(60) which should cover most people's names.

Salary is a decimal with 10 total digits, two on the right hand side of the decimal point. This would handle a salary of up to 99,999,999.99 – again, you're not likely to hit this limit.

Date hired will be a date in this format 2010-05-06. YYYY-MM-DD.

So when considering this simple table, where would you expect to need an index?

If we assign ID as a primary key, we don't need one there.

Indexes are best used on columns that are frequently used in where clauses, and in any kind of sorting, such as "order by".

You should also pay attention to whether or not this information will change frequently, because it will slow down your updates and inserts. Since you wont frequently be adding employees, you don't have to worry about the inserts.

Let's say that you will be looking up the employees with a php web interface and the end user will be typing in the employees name to find them, since remembering the employee ID's would be cumbersome.

It sounds like this situation would be good to use an index.

A – You won't be updating the employee's name very often, so you don't have to worry about a performance hit there.

B – You WILL be using the employee in where clauses like this:
select * from employees where name ='smith';

C – You WILL be generating reports, which will probably be alphabetic, like this:
select * from employees order by name asc;

So in this simple example it's easy to see when it would be important to use indexes.
So, you could do it like this:
create index name_index on employees (name);
You might be working on a more complex database, so it's good to remember a few simple rules.

- Indexes slow down inserts and updates, so you want to use them carefully on columns that are FREQUENTLY updated.
- Indexes speed up where clauses and order by.

Remember to think about HOW your data is going to be used when building your tables.

There are a few other things to remember. If your table is very small, i.e., only a few employees, it's worse to use an index than to leave it out and just let it do a table scan. Indexes really only come in handy with tables that have a lot of rows.

So, if Joe’s Pet Shop was using this database, they would probably be able to leave the index off the "name" column.

If Microsoft was using this database (hah!) they might want to throw and index in there.

Another thing to remember, that is a con in the situation of our employees database, is that if the column is a variable length, indexes (as well as most of MySQL) perform much less efficiently.

As you can see there are many things to consider with indexes, even with a very simple table as this.

Source: http://www.howtoforge.com/when-to-use-indexes-in-mysql-databases

Monday, September 16, 2013

Permanently Delete Old Deleted AdWords Campaigns

For one of my project, I needed to permanently delete old deleted AdWords campaigns. I was wondering if it is possible. But I found an answer regarding "Permanently deletion of Campaigns, adGroups, ads" etc from Google AdWords Team.

"Thank you for your email. I understand that you would like to permanently remove the deleted campaigns from your AdWords account, and also, from AdWords Editor. Please know that while it’s possible for you to delete an active ad, keyword, or campaign, it isn’t possible to permanently delete these. Your historical account data is just as valuable to your ongoing advertising experience as your active campaign information. Therefore, this information remains with your account so that we can provide you with the best advertising performance possible. 
Sincerely, Google Rep
The Google AdWords Team”

Wednesday, September 11, 2013

How to add jQuery table filter?

You can filter a table rows dynamically using jQuery Plugin table filter. The plugin will insert a input form for filtering table rows dynamically.

Demo

Usage:
Download jQuery plugin:
jquery.table-filter.js
Insert to all table:
$("table").addTableFilter();
Insert to "#table1" only:
$("#table1").addTableFilter();
Insert with custom label text and size:
$("table").addTableFilter({
  labelText: "Filtering Words: ",
  size:      48
});
Source: https://github.com/hail2u/jquery.table-filter

Sunday, September 8, 2013

How to integrate Google Adwords API into Codeigniter?

One blogger gave me idea
Just add all the api documents to the third_party folder and require the library from your controller or library and voilĂ !

Figure: Google Adwords API Hierarchy


After many hours of searching, reading and testing I was successful to integrate AdWords API PHP Client Library into Codeigniter 2.X.

Step by step guide on how to integrate Google Adwords API into Codeigniter.
Google Adwords API into Codeigniter
# Steps Description
1. Download AdWords API PHP Client Library This client library makes it easier to write PHP applications that programmatically access the AdWords API or DoubleClick Ad Exchange Buyer API. I have downloaded version 4.5.1(adwords_api_php_4.5.1)
2. Extract the compressed archive (.zip or .tar.gz) and paste the src folder inside codeigniter's third_party folder. Grab only src folder from the compressed files. Create a folder called Adwords inside CodeIgniter’s application/third_party/ and paste src folder inside CodeIgniter’s application/third_party/Adwords/ folder. Your application/third_party/ folder will look like application/third_party/Adwords/src/...
3. Create a php file inside Codeigniter's library folder. Create new PHP file inside Codeigniter’s application/libraries/ name it My_adwords.php
4. Set the correct path to access Adwords API. Check the source code below on how to set the correct path on application/libraries/My_adwords.php. I have added GetCampaigns function (copied from Example folder of google adwords php client library) to check later if it returns any values.
5. Now you can use My_Adwords library in your CodeIgniter’s controller code. Now you can easily access the My_Adwords library from the Codeigniter's controller like any other library methods. I have created a controller called adwords.php inside application/controller/ and call the function to fetch all the active campaigns. You can get the source of controller adwords.php
6. Test the controller and enjoy. Type the 'localhost/your_project_folder/adwords/' in your browser and you can see the result. You can see my result in the end.

Set the correct path on application/libraries/My_adwords.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
define('SRC_PATH', APPPATH.'/third_party/Adwords/src/');
define('LIB_PATH', 'Google/Api/Ads/AdWords/Lib');
define('UTIL_PATH', 'Google/Api/Ads/Common/Util');
define('AW_UTIL_PATH', 'Google/Api/Ads/AdWords/Util');

define('ADWORDS_VERSION', 'v201306');

// Configure include path
ini_set('include_path', implode(array(
    ini_get('include_path'), PATH_SEPARATOR, SRC_PATH))
    );

// Include the AdWordsUser file
require_once SRC_PATH.LIB_PATH. '/AdWordsUser.php';


class My_adwords extends AdWordsUser { 
    public function __construct() { 
       parent::__construct();
    }     
    
 function GetCampaigns() {
   // Get the service, which loads the required classes.
   $campaignService = $this->GetService('CampaignService', ADWORDS_VERSION);
 
   // Create selector.
   $selector = new Selector();
   $selector->fields = array('Id', 'Name');
   $selector->ordering[] = new OrderBy('Name', 'ASCENDING');
 
   // Create paging controls.
   $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
 
   do {
     // Make the get request.
     $page = $campaignService->get($selector);
 
     // Display results.
     if (isset($page->entries)) {
       foreach ($page->entries as $campaign) {
         printf("Campaign with name '%s' and ID '%s' was found.\n",
             $campaign->name, $campaign->id);
       }
     } else {
       print "No campaigns were found.\n";
     }
 
     // Advance the paging index.
     $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
   } while ($page->totalNumEntries > $selector->paging->startIndex);
 }  
}
source code: application/controllers/adwords.php
<?php 
error_reporting(E_STRICT | E_ALL);
ini_set('display_errors', '1');

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Adwords extends CI_Controller{

function __construct()
 {
  parent::__construct(); 
  //load our new Adwords library
  $this->load->library('My_adwords');

 }

 function index()
 {
   $user = new My_adwords();
   $user->GetCampaigns();
 
 }


}
Result
Campaign with name 'Campaign test #1' and ID '150648975' was found. Campaign with name 'Interplanetary Cruise #52299d09d8493' and ID '150652815' was found. Campaign with name 'Interplanetary Cruise #52299d09d8517' and ID '150652935' was found.
Hope you will like my solution. If it helped you to save your time, feedback will be deeply appreciated. :)

Monday, September 2, 2013

Display all php errors and warnings

I am annoyed why my php script doesn't show errors and warnings like it did before. It seems my server admin has default config set not to show the errors and warnings.

Every time I was debugging the code I found myself searching around for the little chunk of code to display all PHP errors and warnings. So, I put in the my post so it was always nearby when I needed.

If you wish to see all the PHP errors and warnings in your script, include the following bit of code to override the php default config setting.

error_reporting(E_ALL);
ini_set('display_errors', '1');