Tuesday, December 25, 2012

Regular expression handler quicker learn in php

Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a







Monday, December 24, 2012

php email reader and notification though header parameters

down vote accepted
For the reading confirmations:
$header.= "X-Confirm-Reading-To: test@test.com\n" ;
 $header.= "Disposition-Notification-To: test@test.com\n";

You have to add the X-Confirm-Reading-To header.
X-Confirm-Reading-To: <address>
For delivery confirmations:
You have to add the Disposition-Notification-To header.

Friday, December 21, 2012

Authorize.net ARB class Automated recurring billing class

<?php

class AuthnetARBException extends Exception {}

class WP_Invoice_AuthnetARB
{
    private $login;
    private $transkey;

    private $params  = array();
    private $sucess  = false;
    private $error   = true;

    var $xml;
    var $response;
    private $resultCode;
    private $code;
    private $text;
    private $subscrId;

    public function __construct()
    {
 
        $this->url = stripslashes(get_option("wp_invoice_recurring_gateway_url"));
        $this->login = stripslashes(get_option("wp_invoice_gateway_username"));
        $this->transkey = stripslashes(get_option("wp_invoice_gateway_tran_key"));

    }

    private function process($retries = 3)
    {
        $count = 0;
        while ($count < $retries)
        {
            $ch = curl_init();
  
   //required for GoDaddy
   if(get_option('wp_invoice_using_godaddy') == 'yes') {
   curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
   curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");
   curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
   }
   //required for GoDaddy

            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->xml);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $this->response = curl_exec($ch);
            $this->parseResults();
            if ($this->resultCode === "Ok")
            {
                $this->success = true;
                $this->error   = false;
                break;
            }
            else
            {
                $this->success = false;
                $this->error   = true;
                break;
            }
            $count++;
        }
        curl_close($ch);
    }

    public function createAccount()
    {
        $this->xml = "<?xml version='1.0' encoding='utf-8'?>
                      <ARBCreateSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>
                          <merchantAuthentication>
                              <name>" . $this->login . "</name>
                              <transactionKey>" . $this->transkey . "</transactionKey>
                          </merchantAuthentication>
                          <refId>" . $this->params['refID'] ."</refId>
                          <subscription>
                              <name>". $this->params['subscrName'] ."</name>
                              <paymentSchedule>
                                  <interval>
                                      <length>". $this->params['interval_length'] ."</length>
                                      <unit>". $this->params['interval_unit'] ."</unit>
                                  </interval>
                                  <startDate>" . $this->params['startDate'] . "</startDate>
                                  <totalOccurrences>". $this->params['totalOccurrences'] . "</totalOccurrences>
                                  <trialOccurrences>". $this->params['trialOccurrences'] . "</trialOccurrences>
                              </paymentSchedule>
                              <amount>". $this->params['amount'] ."</amount>
                              <trialAmount>" . $this->params['trialAmount'] . "</trialAmount>
                              <payment>
                                  <creditCard>
                                      <cardNumber>" . $this->params['cardNumber'] . "</cardNumber>
                                      <expirationDate>" . $this->params['expirationDate'] . "</expirationDate>
                                  </creditCard>
                              </payment>
                              <order>
                                  <invoiceNumber>" . $this->params['orderInvoiceNumber'] . "</invoiceNumber>
                                  <description>" . $this->params['orderDescription'] . "</description>
                              </order>
                              <customer>
                                  <id>" . $this->params['customerId'] . "</id>
                                  <email>" . $this->params['customerEmail'] . "</email>
                                  <phoneNumber>" . $this->params['customerPhoneNumber'] . "</phoneNumber>
                                  <faxNumber>" . $this->params['customerFaxNumber'] . "</faxNumber>
                              </customer>
                              <billTo>
                                  <firstName>". $this->params['firstName'] . "</firstName>
                                  <lastName>" . $this->params['lastName'] . "</lastName>
                                  <company>" . $this->params['company'] . "</company>
                                  <address>" . $this->params['address'] . "</address>
                                  <city>" . $this->params['city'] . "</city>
                                  <state>" . $this->params['state'] . "</state>
                                  <zip>" . $this->params['zip'] . "</zip>
                              </billTo>
                              <shipTo>
                                  <firstName>". $this->params['shipFirstName'] . "</firstName>
                                  <lastName>" . $this->params['shipLastName'] . "</lastName>
                                  <company>" . $this->params['shipCompany'] . "</company>
                                  <address>" . $this->params['shipAddress'] . "</address>
                                  <city>" . $this->params['shipCity'] . "</city>
                                  <state>" . $this->params['shipState'] . "</state>
                                  <zip>" . $this->params['shipZip'] . "</zip>
                              </shipTo>
                          </subscription>
                      </ARBCreateSubscriptionRequest>";
        $this->process();
    }

    public function updateAccount()
    {
        $this->xml = "<?xml version='1.0' encoding='utf-8'?>
                      <ARBUpdateSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>
                          <merchantAuthentication>
                              <name>" . $this->url . "</name>
                              <transactionKey>" . $this->transkey . "</transactionKey>
                          </merchantAuthentication>
                          <refId>" . $this->params['refID'] ."</refId>
                          <subscriptionId>" . $this->params['subscrId'] . "</subscriptionId>
                          <subscription>
                              <name>". $this->params['subscrName'] ."</name>
                              <amount>". $this->params['amount'] ."</amount>
                              <trialAmount>" . $this->params['trialAmount'] . "</trialAmount>
                              <payment>
                                  <creditCard>
                                      <cardNumber>" . $this->params['cardNumber'] . "</cardNumber>
                                      <expirationDate>" . $this->params['expirationDate'] . "</expirationDate>
                                  </creditCard>
                              </payment>
                              <billTo>
                                  <firstName>". $this->params['firstName'] . "</firstName>
                                  <lastName>" . $this->params['lastName'] . "</lastName>
                                  <address>" . $this->params['address'] . "</address>
                                  <city>" . $this->params['city'] . "</city>
                                  <state>" . $this->params['state'] . "</state>
                                  <zip>" . $this->params['zip'] . "</zip>
                                  <country>" . $this->params['country'] . "</country>
                              </billTo>
                          </subscription>
                      </ARBUpdateSubscriptionRequest>";
        $this->process();
    }

    public function deleteAccount()
    {
        $this->xml = "<?xml version='1.0' encoding='utf-8'?>
                      <ARBCancelSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>
                          <merchantAuthentication>
                              <name>" . $this->url . "</name>
                              <transactionKey>" . $this->transkey . "</transactionKey>
                          </merchantAuthentication>
                          <refId>" . $this->params['refID'] ."</refId>
                          <subscriptionId>" . $this->params['subscrId'] . "</subscriptionId>
                      </ARBCancelSubscriptionRequest>";
        $this->process();
    }

    private function parseResults()
    {
        $this->resultCode = $this->parseXML('<resultCode>', '</resultCode>');
        $this->code       = $this->parseXML('<code>', '</code>');
        $this->text       = $this->parseXML('<text>', '</text>');
        $this->subscrId   = $this->parseXML('<subscriptionId>', '</subscriptionId>');
    }

    private function parseXML($start, $end)
    {
        return preg_replace('|^.*?'.$start.'(.*?)'.$end.'.*?$|i', '$1', substr($this->response, 334));
    }

    public function setParameter($field = "", $value = null)
    {
        $field = (is_string($field)) ? trim($field) : $field;
        $value = (is_string($value)) ? trim($value) : $value;
        if (!is_string($field))
        {
            throw new AuthnetARBException("setParameter() arg 1 must be a string or integer: " . gettype($field) . " given.");
        }
        if (!is_string($value) && !is_numeric($value) && !is_bool($value))
        {
            throw new AuthnetARBException("setParameter() arg 2 must be a string, integer, or boolean value: " . gettype($value) . " given.");
        }
        if (empty($field))
        {
            throw new AuthnetARBException("setParameter() requires a parameter field to be named.");
        }
        if ($value === "")
        {
            throw new AuthnetARBException("setParameter() requires a parameter value to be assigned: $field");
        }
        $this->params[$field] = $value;
    }

    public function isSuccessful()
    {
        return $this->success;
    }

    public function isError()
    {
        return $this->error;
    }

    public function getResponse()
    {
        return strip_tags($this->text);
    }

    public function getResponseCode()
    {
        return $this->code;
    }

    public function getSubscriberID()
    {
        return $this->subscrId;
    }
}

?>

Tuesday, December 18, 2012

php image upload class file

<?php

    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
        private $seqnence;
        public $name='Uploader';
        public $useTable    =false;

        function setDir($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }

        function allowAllFormats(){
            $this->allowAll =   true;
        }

        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }

        function setExtensions($options){
            $this->extensions   =   $options;
        }

        function setSameFileName(){
            $this->sameFileName =   true;
            $this->sameName =   true;
        }
        function getExtension($string){
            $ext    =   "";
            try{
                    $parts  =   explode(".",$string);
                    $ext        =   strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext    =   "";
            }
            return $ext;
    }

        function setMessage($message){
            $this->errorMessage =   $message;
        }

        function getMessage(){
            return $this->errorMessage;
        }

        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
            $this->imageSeq =   $seq;
    }

    function getRandom(){
        return strtotime(date('Y-m-d H:i:s')).rand(1111,9999).rand(11,99).rand(111,999);
    }
    function sameName($true){
        $this->sameName =   $true;
    }
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){

        if($this->sameName==false){
                    $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
            $this->uploadName=  $name;
        }
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }

        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }

    }

?>
Now upload files using Uploader class. Use following code . Code block is self explanatory .

<?php

$uploader   =   new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
$uploader->setMaxSize(.5);                          //set max file size to be allowed in MB//

if($uploader->uploadFile('txtFile')){   //txtFile is the filebrowse element name //   
    $image  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

}else{//upload failed
    $uploader->getMessage(); //get upload error message
}


?>

Thursday, December 13, 2012

array pagination using php class

<?php


  class pagination
  {
    var $page = 1; // Current Page
    var $perPage = 10; // Items on each page, defaulted to 10
    var $showFirstAndLast = false; // if you would like the first and last page options.
   
    function generate($array, $perPage = 10)
    {
      // Assign the items per page variable
      if (!empty($perPage))
        $this->perPage = $perPage;
     
      // Assign the page variable
      if (!empty($_GET['page'])) {
        $this->page = $_GET['page']; // using the get method
      } else {
        $this->page = 1; // if we don't have a page number then assume we are on the first page
      }
     
      // Take the length of the array
      $this->length = count($array);
     
      // Get the number of pages
      $this->pages = ceil($this->length / $this->perPage);
     
      // Calculate the starting point
      $this->start  = ceil(($this->page - 1) * $this->perPage);
     
      // Return the part of the array we have requested
      return array_slice($array, $this->start, $this->perPage);
    }
    function getpage($total)
    {
        $perPage=$this->perPage;
        $sratpage=$this->start;
        if($perPage>$total)
         {
                  echo "Results ".($sratpage+1)."-"; echo $total; echo " of ".$total;
         }else{
               
                if($sratpage==0)
                {
                        echo "Results ".($sratpage+1)."-"; echo $perPage; echo " of ".$total;
                }else{
                        $endpage=($sratpage+$perPage);
                        if($endpage>$total)
                        {
                         echo "Results ".$sratpage."-"; echo $total;echo " of ".$total;
                        }
                        else
                        {
               
                        echo "Results ".$sratpage."-"; echo $endpage;echo " of ".$total;
                        }
                           
               
                }
    }
   
  }
    function links()
    {
      // Initiate the links array
      $plinks = array();
      $links = array();
      $slinks = array();
     
      // Concatenate the get variables to add to the page numbering string
      if (count($_GET)) {
        $queryURL = '';
        foreach ($_GET as $key => $value) {
          if ($key != 'page') {
           // $queryURL .= '&'.$key.'='.$value;
          }
        }
      }
     
      // If we have more then one pages
      if (($this->pages) > 1)
      {
        // Assign the 'previous page' link into the array if we are not on the first page
        if ($this->page != 1) {
          if ($this->showFirstAndLast) {
            $plinks[] = ' <a href="?page=1'.$queryURL.'">&laquo;&laquo; First </a> ';
          }
          $plinks[] = ' <span class="paginationPrev"><a href="?page='.($this->page - 1).$queryURL.'">&laquo; Prev</a></span> ';
        }
       
        // Assign all the page numbers & links to the array
        echo '<span nowrap="nowrap" align="center">';
        for ($j = 1; $j < ($this->pages + 1); $j++) {
          if ($this->page == $j) {
            $links[] = ' <span class="selected1">'.$j.'</span> '; // If we are on the same page as the current item
          } else {
            $links[] = ' <a href="?page='.$j.$queryURL.'">'.$j.'</a>'; // add the link to the array
          }
        }
        echo '</span>';
        echo '<span class="paginationNext">';
        // Assign the 'next page' if we are not on the last page
        if ($this->page < $this->pages) {
          $slinks[] = ' <a href="?page='.($this->page + 1).$queryURL.'"> Next &raquo; </a> ';
          if ($this->showFirstAndLast) {
            $slinks[] = ' <a href="?page='.($this->pages).$queryURL.'"> Last &raquo;&raquo; </a> ';
          }
        }
        echo '</span>';
        // Push the array into a string using any some glue
        return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
      }
      return;
    }
  }
?>

Tuesday, December 11, 2012

how to slider bar open using jquery

-----------------------------------------------------------------------------------------------
 <script type="text/javascript" src="<?php bloginfo( 'template_url' ); ?>/js/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        jQuery(".pull_feedback").toggle(function(){
                jQuery("#feedback").animate({left:"0px"});
                return false;
            },
            function(){
                jQuery("#feedback").animate({left:"-527px"});  
                return false;
            }
        ); //toggle
    }); //document.ready
    </script>
-------------------------------------------------------------------------------------------------
<script language="javascript">
function processForm(formId) {
document.getElementById('process').style.display='block';
$.ajax({
type: "GET",
url: "form_ask.php",
data: "sendmsg="+document.getElementById('user_question').value,
success: function(msg)
    {
            //alert(msg);
            document.getElementById('process').style.display='none';
            $('#message').html(msg);
            $('#user_question').val('');
            return true;
    },
    error: function(){
          
            return false;
        //alert('some error has occured...');  
    },
    start: function(){
        alert('ajax has been started...');  
    }
});
}
</script>

--------------------------------------------------------------------------------------------------
<div id="feedback">
<h2>Sikh  Counseling</h2>

<form action="" id="form1" method="post"  onsubmit="processForm('form1');return false;">
<div style="clear:both; padding-bottom: 8px;"></div>
            <div id="message"></div>
            <div id='process' style="display:none"><img src="loading.gif" ></div>
       
           
            <p>           
            <textarea id='user_question'  onfocus="if(this.value=='Type Your Sikh Counseling Question Here...') this.value='';" onblur="if(this.value=='') this.value='Type Your Sikh Counseling Question Here...';">Type Your Sikh Counseling Question Here...</textarea>           
            </p>
            <p class="txt">Sikh Counselors are Online Now</p>
            <p>
            <input type='submit' name='submit' value='submit' class="btn"/>
           
            </p>
        </form>
        <a href="#" class="pull_feedback" title="Click to leave Question">Question</a>
    </div>
------------------------------------------------------------------------------------------

Friday, December 7, 2012

javascrpt captcha

<html>
<head>
<title>Captcha</title>
   
    <script type="text/javascript">

   //Created / Generates the captcha function   
    function DrawCaptcha()
    {
       var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
       var string_length =6;
       var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
          }
      
        document.getElementById("txtCaptcha").value = randomstring
    }

    // Validate the Entered input aganist the generated security code function  
    function ValidCaptcha(){
        var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
        var str2 = removeSpaces(document.getElementById('txtInput').value);
        if (str1 == str2)
           return true;       
        else
        {
            alert("Invalid captcha value");
        return false;
        }
       
    }

    // Remove the spaces from the entered and generated code
    function removeSpaces(string)
    {
        return string.split(' ').join('');
    }
   

    </script>
   
   
   
</head>
<body onLoad="DrawCaptcha();">
<table>
<tr>
    <td>
        Welcome To Captcha<br />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtCaptcha" disabled="true"
            style="background-image:url(captcha_bg.jpg); text-align:center; border:none;
            font-weight:bold; font-family:Arial, Helvetica, sans-serif; font-size:16px;line-height:12px;" />
        <input type="button" id="btnrefresh" value="Refresh"  onClick="DrawCaptcha();return false;" />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtInput"/>   
    </td>
</tr>
<tr>
    <td>
        <input id="Button1" type="button" value="Check" onClick="alert(ValidCaptcha());"/>
    </td>
</tr>
</table>
</body>
</html>

Thursday, December 6, 2012

how to sorting multiple array object in php


sorting multiple array object using php
 function sort_arr_of_obj($array, $sortby, $direction='asc') {
    
    $sortedArr = array();
    $tmp_Array = array();
    
    foreach($array as $k => $v) {
        $tmp_Array[] = strtolower($v->$sortby);
    }
    
    if($direction=='asc'){
        asort($tmp_Array);
    }else{
        arsort($tmp_Array);
    }
    
    foreach($tmp_Array as $k=>$tmp){
        $sortedArr[] = $array[$k];
    }
    
    return $sortedArr;

}


$lowestsellerpricesort= sort_arr_of_obj($response->categories->category->items->product->offers->offer,'basePrice','asc');

how to sort multiple array in php

multiple array sorting using php 
<?php
$multiArray = Array(
    Array("id" => 1, "name" => "Defg","add"=>"adstes"),
    Array("id" => 4, "name" => "Abcd","add"=>"tes"),
    Array("id" => 3, "name" => "Bcde","add"=>"des"),
    Array("id" => 2, "name" => "Cdef","add"=>"cad"));
function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($multiArray,"id");
echo "<pre>";print_r($multiArray);

?>

multiple array sorting using php

Saturday, November 17, 2012

select all data between two dates using mysql

SELECT *
FROM `product`
WHERE (createdate BETWEEN '2012-11-19 14:15:55' AND '2012-11-29 21:58:43');

Hope enjoy:)

htaccess allow access php specific file

<Files ~ "^piwik\.(js|php)|robots\.txt$">
    Allow from all
    Satisfy any
</Files>

how to post data to other page using javascript and php

<script  language="javascript">
function postdatasend(data){
var pnamevalue=document.getElementById('prname'+data).value;
var ppricevalue=document.getElementById('prprice'+data).value;
var mapForm = document.createElement("form");
    mapForm.target = "Map";
    mapForm.method = "POST"; // or "post" if appropriate
    mapForm.action = "showsingleproduct.php";
    mapForm.target='_self';
var pname = document.createElement("input");
    pname.type = "hidden";
    pname.name = "proname";
    pname.value = pnamevalue;   
    mapForm.appendChild(pname);
   
var pprice = document.createElement("input");
    pprice.type = "hidden";
    pprice.name = "proprice";
    pprice.value = ppricevalue;   
    mapForm.appendChild(pprice);
    document.body.appendChild(mapForm);
    mapForm.submit();

return true;
}
</script>

<input type="hidden" id="<?php echo 'prname'.$formcounter?>" name="<?php echo 'pro'.$formcounter?>" value="<?php echo $productArray['Productname']?>">
<input type="hidden" id="<?php echo 'prprice'.$formcounter?>" name="<?php echo 'pro'.$formcounter?>" value="<?php echo $productArray['Price']; ?>">


<a href="javascript:return void(0);" onclick="javascript: return postdatasend('<?php echo $formcounter?>');"> send data</a>

Wednesday, November 14, 2012

shopping.com api using php and xml parsing easily

#create a array pagination class page.
<?php


  class pagination
  {
    var $page = 1; // Current Page
    var $perPage = 10; // Items on each page, defaulted to 10
    var $showFirstAndLast = false; // if you would like the first and last page options.
   
    function generate($array, $perPage = 10)
    {
      // Assign the items per page variable
      if (!empty($perPage))
        $this->perPage = $perPage;
     
      // Assign the page variable
      if (!empty($_GET['page'])) {
        $this->page = $_GET['page']; // using the get method
      } else {
        $this->page = 1; // if we don't have a page number then assume we are on the first page
      }
     
      // Take the length of the array
      $this->length = count($array);
     
      // Get the number of pages
      $this->pages = ceil($this->length / $this->perPage);
     
      // Calculate the starting point
      $this->start  = ceil(($this->page - 1) * $this->perPage);
     
      // Return the part of the array we have requested
      return array_slice($array, $this->start, $this->perPage);
    }
   
    function links()
    {
      // Initiate the links array
      $plinks = array();
      $links = array();
      $slinks = array();
     
      // Concatenate the get variables to add to the page numbering string
      if (count($_GET)) {
        $queryURL = '';
        foreach ($_GET as $key => $value) {
          if ($key != 'page') {
            $queryURL .= '&'.$key.'='.$value;
          }
        }
      }
     
      // If we have more then one pages
      if (($this->pages) > 1)
      {
        // Assign the 'previous page' link into the array if we are not on the first page
        if ($this->page != 1) {
          if ($this->showFirstAndLast) {
            $plinks[] = ' <a href="?page=1'.$queryURL.'">&laquo;&laquo; First </a> ';
          }
          $plinks[] = ' <span class="paginationPrev"><a href="?page='.($this->page - 1).$queryURL.'">&laquo; Prev</a></span> ';
        }
       
        // Assign all the page numbers & links to the array
        echo '<span nowrap="nowrap" align="center">';
        for ($j = 1; $j < ($this->pages + 1); $j++) {
          if ($this->page == $j) {
            $links[] = ' <span class="selected1">'.$j.'</span> '; // If we are on the same page as the current item
          } else {
            $links[] = ' <a href="?page='.$j.$queryURL.'">'.$j.'</a>'; // add the link to the array
          }
        }
        echo '</span>';
  echo '<span class="paginationNext">';
        // Assign the 'next page' if we are not on the last page
        if ($this->page < $this->pages) {
          $slinks[] = ' <a href="?page='.($this->page + 1).$queryURL.'"> Next &raquo; </a> ';
          if ($this->showFirstAndLast) {
            $slinks[] = ' <a href="?page='.($this->pages).$queryURL.'"> Last &raquo;&raquo; </a> ';
          }
        }
        echo '</span>';
        // Push the array into a string using any some glue
        return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
      }
      return;
    }
  }
?>

-------------------------------End pagination class-----------------------------------------

#include pagination class 

#shopping.com api implement using php(shopapi.php) ;
<div class="proright">

<?php
 include('php_array_pagingnation.php');
$requey=$_REQUEST['categoryname'];

$response = new SimpleXMLElement(
    "http://sandbox.api.shopping.com/publisher/3.0/rest/GeneralSearch?apiKey=authorized-key&trackingId=7000610&keyword=$requey&numItems=1000",
    null,
    true
);

echo "<pre>";print_r($response);
?>

<div class="main_cart">
<?php
echo "<span style=\"padding-left:5px;\"><h2>$requey</h2></span>";
//print_r($response);
$pagination = new pagination;
  foreach ($response->categories->category->items->product as $value) {
          $products[] = array(
            'Productname' => $value->name,
            'productOffersURL' => $value->productOffersURL,
            'sourceURL' => $value->images->image->sourceURL,
            'storeNotes' => $value->numStores,
            'Price' => $value->minPrice,
             'reviewURL' => $value->rating->reviewURL,
            'reviewCount' => $value->rating->reviewCount,
            'ratingImage' => $value->rating->ratingImage->sourceURL,
          );
        }
       
        // If we have an array with items
        if (count($products)) {
          // Parse through the pagination class
          $productPages = $pagination->generate($products, 40);
          // If we have items
          if (count($productPages) != 0) {
            // Create the page numbers
            echo $pageNumbers = '<div class="paginationNew"><div class="numbers">'.$pagination->links().'</div></div>';
            // Loop through all the items in the array
foreach ($productPages as $productArray) {?>
     
             
                <div class="cart_det">
                <a href="<?php echo $productArray['productOffersURL']; ?>" target="_blank"><img src="<?php echo $productArray['sourceURL']; ?>" width="152" height="150"/></a>
                <div class="name"> <a href="<?php echo $productArray['productOffersURL']; ?>" target="_blank"><?php echo $productArray['Productname']; ?></a></div>
                <ul class="rate_det">
                <li class="price">From $<?php echo $productArray['Price']; ?></li>
                <li class="shiping">Free Shipping</li>
                <li class="story" ><?php echo $productArray['storeNotes']; ?> stores</li>
                 <li class="reviewno" >
                <?php if(!empty($productArray['reviewURL'])){?>
                  <a href="<?php echo $productArray['reviewURL']; ?>" target="_blank">Reviews (<?php echo $productArray['reviewCount']; ?>) </a>           
                <?php }else{?>&nbsp;
                    <?php }?>
                </li> 
                <li class="ratingimg">   
                <?php if(!empty($productArray['ratingImage'])){?>
                   
                <img src="<?php echo $productArray['ratingImage']; ?>" border="0" width="91">               
                               
                <?php }else{?>
                    <img src="images/sdc_stars_sm_blnk.gif" border="0" width="91">       
                    <?php }?>
                </li>
                </ul>
               
                </div>
        
            <?php }
            // print out the page numbers beneath the results
      
          }
         
        }


?>
</div>

<?php echo $pageNumbers = '<div class="numbers">'.$pagination->links().'</div>';?>

</div>

Sunday, November 11, 2012

how to add rows number using mysql query


select @rownum:=@rownum+1 ‘rowid’, p.* from menu p,  
(SELECT @rownum:=0) r order by id desc limit 10;

Thursday, November 8, 2012

create dynamic main menu and sub menu using php and mysql

<?php
CREATE TABLE `menu` (
  `id` int(11) NOT NULL auto_increment,
  `label` varchar(50) NOT NULL default '',
  `link` varchar(100) NOT NULL default '#',
  `parent` int(11) NOT NULL default '0',
  `sort` int(11) default NULL,
  PRIMARY KEY  (`id`))
------------------------------------------------------------------------------------------------------
$mysql=mysql_connect('127.0.0.1','root','');
mysql_select_db('test',$mysql);
function display_menu($parent, $level) {
    $result = mysql_query("SELECT a.id, a.label, a.link, Deriv1.Count FROM `menu` a  LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent);
    echo "<ul>";
    while ($row = mysql_fetch_assoc($result)) {
        if ($row['Count'] > 0) {
            echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a>";
            display_menu($row['id'], $level + 1);
            echo "</li>";
        } elseif ($row['Count']==0) {
            echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>";
        } else;
    }
    echo "</ul>";
}
display_menu(0, 1);
?>

Tuesday, November 6, 2012

how to set custom page title in wordpress

 how to set custom page title in wordpress
<?php
function add_custom_title() {


         <title>call bikash page title</title>


}
add_action('wp_head','add_custom_title');
?>

Friday, October 19, 2012

create wsdl for sending email using soap and php

create simple wsdk webservice using php
--------------------------create wsdl using my code simple php --------------------------------------------
//step 1 create index.php
<?php
// Author by bikash ranajn nayak
require_once('../lib/nusoap.php');

$server = new nusoap_server;

$server->configureWSDL('server', 'urn:server');

$server->wsdl->schemaTargetNamespace = 'urn:server';
 $server->wsdl->addComplexType('Emailsend','complexType','struct','all','',
array(
'To' => array('name' => 'ToEmailid','type' => 'xsd:int'),
'From' => array('name' => 'FromEmailid','type' => 'xsd:string'),
'Subject' => array('name' => 'Subject','type' => 'xsd:string'),
'Message' => array('name' => 'MessageBody','type' => 'xsd:string')


));

$server->register('Emailsend',
            array('servicebybikash' => 'xsd:string'),   
            array('return' => 'xsd:string'),
            'urn:server',
            'urn:server#functions');

function Emailsend($to,$from,$subject,$messagebody)

$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
if(mail($to,$subject,$messagebody,$headers)){
  return true;
}else{
return false;
}
  
}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';

$server->service($HTTP_RAW_POST_DATA);
?>


-----------call wsdl index.php service using  php soap------------------------------------

 create a page call the wsdl service using php

<?php
/*
 *   auther by bikash
 *
 *    Client sample.
 *
 *    Service: SOAP endpoint
 *    Payload: rpc/encoded
 *    Transport: http
 *    Authentication: none
 */
require_once('../lib/nusoap.php');
$client = new soapclient('http://bikashnayak.com/samples/index.php?wsdl');
$htmldbody="<h1>helow bikash kese ho</h1>";
$res=$client->__call('Emailsend',array('to'=>'bikash@techwave.com','from'=>
'shamim@techwave.com','helo i shamaim',$htmldbody));
if($client->fault)
   {
      echo "Fault: <p>Code: {$client->faultcode}<br>";
      echo "String: {$client->faultstring}";
   }
   else
   {
   echo '<pre>' . htmlspecialchars($client->return, ENT_QUOTES) . '</pre>';
    echo "success fully sent mail";
   }

?>

json return using soap server and soap client using php


How to get JSON response from SOAP Call in PHP
copy soap_server page like (index.php);
-----------------------------------------------------------------------
require_once('../lib/nusoap.php');

$server = new nusoap_server;

$server->configureWSDL('server', 'urn:server');

$server->wsdl->schemaTargetNamespace = 'urn:server';

$server->register('getrequest',
            array('name' => 'xsd:string'),       
            array('return' => 'xsd:string'),
            'urn:server',
            'urn:server#getrequest');

function getrequest($value,$address)
{
   $getval=array('name'=>$value,'address'=>$address);
  
   return json_encode($getval);
    
}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';

$server->service($HTTP_RAW_POST_DATA);
?>
------------------------------------------------------------------------------------
create soap client page (get json data form soap)getdata.php
----------------------------------------------------------------------------
require_once('../lib/nusoap.php');
$client = new soapclient('http://127.0.0.1/test/nusoap/samples/index.php?wsdl');

$res=$client->__call('getrequest',array('name'=>'bikash','address'=>'teliakan'));
if($client->fault)
   {
      echo "Fault: <p>Code: {$client->faultcode}<br>";
      echo "String: {$client->faultstring}";
   }
   else
   {
    echo $res;
   }

how to create nusoap_server and nusoap_client implemention using php

1st-> download nusoap class library 
2nd->create wsdl function "getrequest()" using below code
your WSDL url could be (http://127.0.0.1/test/nusoap/samples/index.php?wsdl)
--------------------index.php--------------------------------------------
require_once('../lib/nusoap.php');

$server = new nusoap_server;

$server->configureWSDL('server', 'urn:server');

$server->wsdl->schemaTargetNamespace = 'urn:server';

$server->register('getrequest',
            array('value' => 'xsd:string'),
            array('return' => 'xsd:string'),
            'urn:server',
            'urn:server#pollServer');

function getrequest($value){

     if($value=="bikash"){
     return "well come  bikash";
     }else{
       return "not bikash";
     }
    
}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';

$server->service($HTTP_RAW_POST_DATA);
------------------------------end nusoap server-------------------------------------------------------

3rd-> call  the wsdl what you create
-------------------------------------------------

create nusoapcallwsdl.php
past below my code


require_once('../lib/nusoap.php');
$client = new soapclient('http://127.0.0.1/test/nusoap/samples/index.php?wsdl');

$res=$client->__call('getrequest',array('bikash'));
print_r($res);

Wednesday, October 17, 2012

how to get post image from attached using id in wordpress

how to get post image in wordpress 
how to  get attached id through post id in worpress


$args = array(
    'numberposts' => 1,
    'order'=> 'DESC',
    'post_mime_type' => 'image',
    'post_parent' =>$post->id,
    'post_type' => 'attachment'
    );

$get_children_array = get_children($args,ARRAY_A);  //returns Array ( [$image_ID]...
$rekeyed_array = array_values($get_children_array);
$child_image = $rekeyed_array[0];
echo '<img src="'.wp_get_attachment_thumb_url($child_image['ID']).'" class="current">';

using post id get image form post data wordpress

Monday, October 15, 2012

point to currency convert from payal to customer using php

point convert to currency to  paypal using php
$success = false;
if($task == 'pay' && $point && $user_points > $point && $mail != '' && $point >= 1000)
{
    $environment = 'live';    // or 'beta-sandbox' or 'live'
    function PPHttpPost($methodName_, $nvpStr_) {
        global $environment, $setting;
        $API_UserName = urlencode($setting['setting_paypal_api_user']);
        $API_Password = urlencode($setting['setting_paypal_api_pass']);
        $API_Signature = urlencode($setting['setting_paypal_api_sign']);
        $API_Endpoint = "https://api-3t.paypal.com/nvp";
        if("sandbox" === $environment || "beta-sandbox" === $environment) {
            $API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
        }
        $version = urlencode('51.0');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
        curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
        $httpResponse = curl_exec($ch);
        if(!$httpResponse) {
            exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
        }
        $httpResponseAr = explode("&", $httpResponse);
        $httpParsedResponseAr = array();
        foreach ($httpResponseAr as $i => $value) {
            $tmpAr = explode("=", $value);
            if(sizeof($tmpAr) > 1) {
                $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
            }
        }
        if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
            exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
        }
        return $httpParsedResponseAr;
    }
   
    $emailSubject =urlencode($setting['setting_paypal_api_user']);
    $receiverType = urlencode('EmailAddress');
    $currency = urlencode('USD');
    $nvpStr="&EMAILSUBJECT=$emailSubject&RECEIVERTYPE=$receiverType&CURRENCYCODE=$currency";
    $receiverEmail = urlencode($mail);
    $amount = urlencode($point / 100);
    $uniqueID = urlencode($user->user_info['user_id']);
    $note = urlencode('note');
    $nvpStr .= "&L_EMAIL0=$receiverEmail&L_Amt0=$amount&L_UNIQUEID0=$uniqueID&L_NOTE0=$note";
    $httpParsedResponseAr = PPHttpPost('MassPay', $nvpStr);
    if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
        $success = true;
        $cash = ($point / 100);
        $msg = "You have successfully exchanged $point points for $$cash!";
          userpoints_deduct($user->user_info['user_id'], $point);
        $database->database_query("INSERT INTO `ememo_socialdb`.`se_redeem_points` (`redeem_id`, `redeem_user`, `redeem_points`, `redeem_cash`, `redeem_date`) VALUES (NULL, '{$user->user_info[user_id]}', '$point', '$cash', UNIX_TIMESTAMP());");
    } else  {
        $success = true;
        $msg = 'Enter valid transaction information';
        print_r($httpParsedResponseAr);
      }
}
elseif($task == 'pay' && $user_points < $point)
{
    $success = true;
    $msg = 'You don\'t have enough points';

}
elseif($task == 'pay' && $point < 1000)
{
    $success = true;
    $msg = '1000 points is the minimal amount to redeem';

}
elseif($task == 'pay' && $mail == '')
{
    $success = true;
    $msg = 'Enter a valid PayPal e-mail address';

}

Wednesday, October 10, 2012

how to encode and decode html tag using php


how to encode and decode html tag using php
you can encode using ->
html_entities(mysql_real_escape_string($variable));

you can decoe using
html_entity_decode(stripslashes($variable));

Tuesday, October 9, 2012

how to remove html tag in a string using php

<?php
    $input = "<div id='bikash'><b>this is the html tag remove in php</b></div><strong>me use for html you do nt use</strong>";

   echo  $b = strip_tags($input, "<strong><em>");
?>

Saturday, October 6, 2012

how to add new custom field virtuemart product category fields in joomla administrator

how to add new field from category virtuemart joomla
execute query for add new category fields
1stp->   ALTER TABLE `jos_vm_category` ADD ` cat_wholesaler` VARCHAR( 1 ) NOT NULL DEFAULT 'N' AFTER `products_per_row` ;

2stp-> GO TO D:\xampp\htdocs\mil-bar\administrator\components\com_virtuemart\html\product.product_category_form.php open
add your field in product.product_category_form.php

      if ($db->sf("cat_wholesaler")=="Y")
         {
          echo "<input type=\"checkbox\" name=\"accesscat\" value=\"Y\" checked=\"checked\" />";
         }else{
          echo "<input type=\"checkbox\" name=\"accesscat\" value=\"Y\" />";
         }

2stp->  administrator/components/com_virtuemart/classes/ps_product_category.php in (function add( &$d ))

a. first get new field value for insert paste below code line 253

      if (vmGet($d,'accesscat')==''){
                 $waccess='N';
        }else{
                 $waccess='Y';
              }

$fields = array('vendor_id' => $ps_vendor_id,
    'category_name' => vmGet( $d, 'category_name' ),
    'category_publish' => vmGet( $d, 'category_publish' ),
    'category_description' => vmGet( $d, 'category_description', '',VMREQUEST_ALLOWHTML ),
        'category_browsepage' => vmGet( $d, 'category_browsepage' ),
    'products_per_row' => vmRequest::getInt( 'products_per_row' ),
    'cat_wholesaler'=>$waccess,
    'category_flypage' => vmGet( $d, 'category_flypage' ),
    'category_thumb_image' => vmGet( $d, 'category_thumb_image' ),
    'category_full_image' => vmGet( $d, 'category_full_image' ),
    'cdate' => $timestamp,
    'mdate' => $timestamp,
    'list_order' => $list_order,
    );

b. for update field value from database same page line  315(function update(&$d))

                       if (vmGet($d,'accesscat')=='')
                          {
                 $waccess='N';
              }else{
                 $waccess='Y';
              }

$fields = array('category_name' => vmGet( $d, 'category_name' ),
           'category_publish' => vmGet( $d, 'category_publish' ),
           'category_description' => vmGet( $d, 'category_description', '',VMREQUEST_ALLOWHTML ),
       'category_browsepage' => vmGet( $d, 'category_browsepage' ),
                                        'products_per_row' => vmRequest::getInt( 'products_per_row' ),
                                        'cat_wholesaler'=> $waccess,
                                        'category_flypage' => vmGet( $d, 'category_flypage' ),
                                        'category_thumb_image' => vmGet( $d, 'category_thumb_image' ),
                                        'category_full_image' => vmGet( $d, 'category_full_image' ),
                                        'mdate' => $timestamp,
                                        'list_order' => vmRequest::getInt('list_order'),
                                    );


lastly enloy your custom field has been added you can insert value and update successfully in virtuemart

Thursday, October 4, 2012

How to prevent mysql injection in Php before it is submitted



SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

 This is the important bit, we take the $username and $password variables that we just filled with data, and we use the function mysql_real_escape_string
on it, what this does is remove and characters that should not be in there, it actually does the same job as stripslashes() apart from this is the correct
method used for MYSQL Databases.

The rest of the code is pretty much self explanatory, after we have checked all the data and made it A-Z characters, we then perform the mysql
query on the database and then we just check the returned information with a series of IF statement, these are all very self explanatory.

This concludes this article, for more information on this subject, checkout www.php.net this website is filled with information on everything php.

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
  1. Using PDO:
    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    
    $stmt->execute(array(':name' => $name));
    foreach ($stmt as $row) {
        // do something with $row
    }
    
  2. Using mysqli:
    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);
    
    $stmt->execute();
    
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row
    }
    

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And gives the developer the chance to catch any error(s) (which are throwed as PDOExceptions.
What is mandatory however is the setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it the the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE * FROM employees the result would simply be a search for the string "'Sarah'; DELETE * FROM employees", and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $unsafeValue));




 

MySQL & PHP Code:

// a good user's name
$name = "timmy"; 
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";

// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad; 
 

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1'' 
 
 

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'"; 

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''
Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''
 
 

prime number using for loop in php





php using prime number program
for($i=2;$i<50;$i++){
$counter=0;
for($j=2;$j<$i;$j++){
if($i%$j==0){
$counter++;
break;
}
}
// you can check instead if($i==$j)
if($counter==0){
echo $i.",";
}
}