Wednesday, September 4, 2013

Concatenate/concat/group_concat two columns/rows with MySQL query

Two/more rows concatenate-
You can use GROUP_CONCAT.
As in:
select person_id, group_concat(hobbies separator ', ')
    from peoples_hobbies group by person_id;
Death: As Dag stated in his comment, there is a 1024 byte limit on result. to solve this run this query before your query:
set group_concat_max_len=2048
Off course, you can change 2048 accourding to your needs.

Two/more columns concatenate-
You can use the CONCAT function like this:
SELECT CONCAT(SUBJECT, ' ', YEAR) FROM table

MySql cast or convert data(integer, float, double, decimal, date, etc...) as character/string

Fiddle link

You will need to cast or convert as a CHAR datatype, there is no varchar datatype that you can cast/convert data to:
select CAST(id as CHAR(50)) as col1 from t9;

select CONVERT(id, CHAR(50)) as colI1 from t9;
select CAST(amount AS DECIMAL(10, 2)) AS amount FROM t9; 

Monday, September 2, 2013

PayPal IPN/Hosted payment with PHP

Create a PayPal Sandbox Account

If you have not done so already, you should have a PayPal Sandbox account setup with two test accounts, one as a test buyer and one as a test seller. The sandbox allows you to test transactions and IPN processing without having to perform live transactions. Follow the instructions in the Sandbox User Guide to setup your accounts or view IPN Guid. 

Creating a Business test account:

The Sandbox automatically creates your first Business test account when you sign-up for a Developer account on developer.paypal.com. PayPal generates the test Business account name by appending -facilitator to your email name, and the account is assigned a set of Classic test API credentials that you can use to create mock PayPal transactions in the Sandbox.
To test Classic API calls, use test Business account values along with values from a Personal test account that you create (as described in Creating a Personal test account).
Some PayPal calls involve more than a single buyer and seller pair. In the testing phase, you need to create all the test accounts needed to fulfill the user entities that partake in your PayPal transactions. For example, parallel payment calls and Adaptive calls each require two different Business accounts, but for different reasons. In these cases, you need to create additional Business test accounts to play the roles of the entities in your transactions.
For more information on the different test account roles, see Planning your Test Accounts.

Accepting credit cards in test transactions


To use a credit card as a payment method in your test transactions, you must configure a test Business account as a PayPal Payments Pro account:
  1. Create a test Business account.
  2. Navigate to the Profile page of the Business account and click the Upgrade to Pro link.
  3. Click Enable on the resulting screen.
Tip  Once you enable PayPal Payments Pro for a test Business account, the setting is permanent and you cannot undo the configuration for that account. We recommend you create multiple Business test accounts with various settings in order to test all the variations you might need to handle with your application.

Getting your API test credentials


All PayPal API requests require API credentials to verify the call is being made through a valid PayPal account. Calls to the Sandbox environment are no different, but they require that you use the test credentials assigned to one of your Sandbox Business accounts. For details on the credentials you need for a specific API call, refer to the API Reference for the PayPal operation(s) you’re using.
The Sandbox assigns each Business account a set of Classic API test credentials. Get your test credentials by navigating to the Profile > API credentials tab of the Business account you want to use in your request:














Create a html file to show form as follows:

<!-- LIVE URL=https://www.paypal.com/cgi-bin/webscr -->
<!-- TEST URL=https://www.sandbox.paypal.com/cgi-bin/webscr -->
<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_xclick"/>
<input type="hidden" name="business" value="pritomkucse@gmail.com"/>
<input type="hidden" name="currency_code" value="USD"/>
<input type="hidden" name="item_name" value="Payment for Order100"/>
<input type="hidden" name="item_number" value="100"/>
<input type="hidden" name="amount" value="100.00"/>
<input type="hidden" name="zip" value="2102"/>
<input type="hidden" name="return" value="http://domain.com/return.php"/>
<input type="hidden" name="notify_url" value="http://domain.com/process.php"/>
<input type="submit" value="Pay"/>
</form>

Now create process.php as follows:
 

$TEST_MODE = true;

// STEP 1: read POST data
$myPost = array();
foreach ($_POST as $key => $val) {
  $myPost[$key] = $val;
}
if(count($myPost) > 0) {
    // read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
    $req = 'cmd=_notify-validate';
    if(function_exists('get_magic_quotes_gpc')) {
        $get_magic_quotes_exists = true;
    } 
    foreach ($myPost as $key => $value) {        
        if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) { 
            $value = urlencode(stripslashes($value)); 
        } else {
            $value = urlencode($value);
        }
        $req .= "&$key=$value";
    }
    // Step 2: POST IPN data back to PayPal to validate
    $ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    /* Un-comment the following line when using in live mode */
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    /* Comment the following line when using in live mode */
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
    if( !($res = curl_exec($ch)) ) {
        echo ("Got " . curl_error($ch) . " when processing IPN data");
        curl_close($ch);
        exit;
    }
    curl_close($ch);
    // inspect IPN validation result and act accordingly
    if (strcmp ($res, "VERIFIED") == 0 || $TEST_MODE) {
        // The IPN is verified, process it:
        // check whether the payment_status is Completed
        // check that txn_id has not been previously processed
        // check that receiver_email is your Primary PayPal email
        // check that payment_amount/payment_currency are correct
        // process the notification
        // IPN message values depend upon the type of notification sent.
        // To loop through the &_POST array and print the NV pairs to the screen:
        foreach($_POST as $key => $value) {
          echo $key." = ". $value."<br>";
        }
    } else if (strcmp ($res, "INVALID") == 0) {
        // IPN invalid, log for manual investigation
        echo "The response from IPN was: <b>" .$res ."</b>";
    }
    return;
}

Output will be something like this if verified or use test mode


mc_gross = 100.00
protection_eligibility = Eligible
address_status = confirmed
payer_id = 2WA3LGLDXB2KQ
tax = 0.00
address_street = 1 Main St
payment_date = 06:19:41 Mar 31, 2014 PDT
payment_status = Completed
charset = windows-1252
address_zip = 95131
first_name = pritomkucse
mc_fee = 3.20
address_country_code = US
address_name = pritomkucse pritomkucse
notify_version = 3.7
custom = 
payer_status = verified
business = pritomkucse@gmail.com
address_country = United States
address_city = San Jose
quantity = 1
payer_email = pritomkucse200@gmail.com
verify_sign = AFcWxV21C7fd0v3bYYYRCpSSRl31AR242OK8FeXkiwjD5hZ5C9sCiKea
txn_id = 9W334245KE956841G
payment_type = instant
last_name = pritomkucse
address_state = CA
receiver_email = pritomkucse@gmail.com
payment_fee = 3.20
receiver_id = GMMFRVHKPYGGG
txn_type = web_accept
item_name = Payment for Order100
mc_currency = USD
item_number = 100
residence_country = US
test_ipn = 1
handling_amount = 0.00
transaction_subject = 
payment_gross = 100.00
shipping = 0.00
auth = Adp..e2JobuposYLNuFxaf24yXSCLj65T4NRjjTYGlW4NwGsFhhT6buQBNhlJyh1RDz6rCb-zHxuG-eEiDlR8Og

Sunday, August 25, 2013

HowTo Format Date For Display or Use In a Shell Script

How do I format date to display on screen on for my shell scripts as per my requirements on Linux or Unix like operating systemsYou need to use the standard date command to format date or time. You can use the same command with the shell script.
 The syntax is
  1. date +FORMAT 
  2. date +"%FORMAT"
  3. date +"%FORMAT%FORMAT" 
  4. date +"%FORMAT-%FORMAT"

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +"%m-%d-%y"Sample output:
02-27-07
To turn on 4 digit year display:
$ date +"%m-%d-%Y"Just display date as mm/dd/yy format:
$ date +"%D"

Task: Display time only

Type the following command:
$ date +"%T"Outputs:
19:55:04
To display locale's 12-hour clock time, enter:
$ date +"%r"Outputs:
07:56:05 PM
To display time in HH:MM format, type:
$ date +"%H-%M"Sample outputs:
00-50

How do I save time/date format to the shell variable?

$ NOW=$(date +"%m-%d-%Y"To display a variable use echo / printf command:
$ echo $NOW

A sample shell script

#!/bin/bash
NOW=$(date +"%m-%d-%Y")
FILE="backup.$NOW.tar.gz"
echo "Backing up data to /nas42/backup.$NOW.tar.gz file, please wait..."
# rest of script
# tar xcvf /nas42/backup.$NOW.tar.gz /home/ /etc/ /var
 

A complete list of FORMAT control characters supported by the date command

FORMAT controls the output. It can be the combination of any one of the following:
%FORMAT StringDescription
%%a literal %
%alocale's abbreviated weekday name (e.g., Sun)
%Alocale's full weekday name (e.g., Sunday)
%blocale's abbreviated month name (e.g., Jan)
%Blocale's full month name (e.g., January)
%clocale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%Ccentury; like %Y, except omit last two digits (e.g., 21)
%dday of month (e.g, 01)
%Ddate; same as %m/%d/%y
%eday of month, space padded; same as %_d
%Ffull date; same as %Y-%m-%d
%glast two digits of year of ISO week number (see %G)
%Gyear of ISO week number (see %V); normally useful only with %V
%hsame as %b
%Hhour (00..23)
%Ihour (01..12)
%jday of year (001..366)
%khour ( 0..23)
%lhour ( 1..12)
%mmonth (01..12)
%Mminute (00..59)
%na newline
%Nnanoseconds (000000000..999999999)
%plocale's equivalent of either AM or PM; blank if not known
%Plike %p, but lower case
%rlocale's 12-hour clock time (e.g., 11:11:04 PM)
%R24-hour hour and minute; same as %H:%M
%sseconds since 1970-01-01 00:00:00 UTC
%Ssecond (00..60)
%ta tab
%Ttime; same as %H:%M:%S
%uday of week (1..7); 1 is Monday
%Uweek number of year, with Sunday as first day of week (00..53)
%VISO week number, with Monday as first day of week (01..53)
%wday of week (0..6); 0 is Sunday
%Wweek number of year, with Monday as first day of week (00..53)
%xlocale's date representation (e.g., 12/31/99)
%Xlocale's time representation (e.g., 23:13:48)
%ylast two digits of year (00..99)
%Yyear
%z+hhmm numeric timezone (e.g., -0400)
%:z+hh:mm numeric timezone (e.g., -04:00)
%::z+hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::znumeric time zone with : to necessary precision (e.g., -04, +05:30)
%Zalphabetic time zone abbreviation (e.g., EDT)
SEE ALSO: