Saturday 30 January 2016

Insert Csv File Data in Mysql using Php with Validation

Insert Csv File Data in Mysql using Php with Validation  Full Example

Sample Csv File Test.csv

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>

<script type="application/javascript">
$(document).ready(function(e) {
    $('#pincodeList').validate({
        rules: {
            Csv: {
                required: true,
extension: "xls|csv"
              
            }

        },

    messages: {
        Csv: {
            extension: 'Please upload a csv file!'
        }
}

    });
});
</script>

<?php
include('connect.php');


if($_POST['submit']){
$csv_file = $_FILES['Csv']['name'];
$tmpFilePath =$_FILES['Csv']['tmp_name'];
$newFilePath="pincodeUpload/";
$mypath = "pincodeUpload/".$csv_file;
move_uploaded_file($tmpFilePath, $mypath);
if ( ! is_dir($newFilePath)) {

mkdir($newFilePath);

$csv_file =$mypath;

if (($handle = fopen($csv_file, "r")) !== FALSE) {

   fgetcsv($handle);  
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
         $num = count($data);
        for ($c=0; $c < $num; $c++) {
           $col[$c] = $data[$c];
        }

    $col1 = $col[0];

  
// SQL Query to insert data into DataBase
$query = "INSERT INTO pincode(Pincode) VALUES('$col1')";
$s     = mysql_query($query);
 }
    fclose($handle);
}

}

?>

<form id="pincodeList" name="pincodeList" method="post" enctype="multipart/form-data">
               <div class="row">
               <div class="co-md-3 col-sm-6">
<input  type="file" name="Csv" >
                </div>
                <div class="co-md-3 col-sm-6">
<input class="btn btn-success" type="submit" name="submit" value="Upload Csv"/>
                </div>
                </div>
</form>

File or Image Upload Validation using Jquery Validation

File or Image Upload Validation using Jquery Validation Example

$("#form1").validate({

        rules: {
        
categoryBanner:{

filesize:1048576
},
        },
messages: { categoryBanner: "File must be JPG, GIF or PNG, less than 1MB" },


        highlight: function(element) {
            $(element).css({
                "background-color": "rgba(60, 141, 188, 0.52)",
                "border-color": "red"
            });
        },
        unhighlight: function(element) {
            $(element).css({
                "background-color": "",
                "border-color": ""
            });
        }

    });

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (in bytes)
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param)
});

<input type="file" name="categoryBanner" />
<input type="submit" name="submit"/>

Wednesday 20 January 2016

Upload Multiple-image Using Webservice in PHP



Hello
Upload Multiple-image Using Webservice in PHP

<?php



 
  if(isset($_POST['submit'])){
 
 
for($i=0; $i<count($_FILES['upload']['name']); $i++) {

/** valiation  only 1 Mb File Upload **/
if($_FILES['upload']['size'][$i] > 1048576){
$notice_image = '<div class="alert alert-info fade in">
    <a title="close" aria-label="close" data-dismiss="alert" class="close" href="#">×</a>
    <strong>Info!</strong> Image Size Must Be Less Than 1 Mb. Your Image is "'.$_FILES['upload']['name'][$i].'"
</div>';

}else{

$tmpFilePath =$_FILES['upload']['tmp_name'][$i];


//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "ProductImg/";

if ( ! is_dir($newFilePath)) {

mkdir($newFilePath);


$picture =uniqid()."_".$_FILES['upload']['name'][$i];
$mypath = "ProductImg/".$picture;
//Upload the file into the temp dir
// if(move_uploaded_file($tmpFilePath, $mypath)) {
if(!file_exists($mypath)){
//move_uploaded_file($tmpFilePath, $mypath);
/** remove Comment when not use webservice*/

 
 
if(!empty($picture))
  {

 
$data = base64_decode($_FILES['upload']['name'][$i]);
$file = fopen($mypath, "w");
fwrite($file,$data);
fclose($file);
  }


}

}


}
}

}
?>

<form method="post" enctype="multipart/form-data">
<?php echo $notice_image; ?>
<input type="file" name="upload[]" multiple="multiple" >
<input type="submit" name="submit" value="save">

</form>

Monday 18 January 2016

Get longitude and latitude using address with php

Get longitude and latitude using address with php 

here The Example For that.

function Get_LatLng_From_Google_Maps($address) {
    $address = urlencode($address);

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";

    // Make the HTTP request
    $data = @file_get_contents($url);
    // Parse the json response
    $jsondata = json_decode($data,true);

    // If the json data is invalid, return empty array
    if (!check_status($jsondata))   return array();

    $LatLng = array(
        'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
        'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
    );

    return $LatLng;
}

/*
* Check if the json data from Google Geo is valid
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}
$address="bhavnagar,gujrat,india";
$arry_lat_lag = Get_LatLng_From_Google_Maps($address);

Monday 4 January 2016

Customize single product page in woocommerce


All function call in wc-template-function.php file check it
location is woocommerce/include/
if you change position of product title,single rating,single price,description,add to cart then

follow below code.

go to content-single.php file

<div class="summary entry-summary">

<?php
/**
* woocommerce_single_product_summary hook
*
* @hooked woocommerce_template_single_title - 5
* @hooked woocommerce_template_single_rating - 10
* @hooked woocommerce_template_single_price - 10
* @hooked woocommerce_template_single_excerpt - 20
* @hooked woocommerce_template_single_add_to_cart - 30
* @hooked woocommerce_template_single_meta - 40
* @hooked woocommerce_template_single_sharing - 50
*/
//do_action( 'woocommerce_single_product_summary' );

woocommerce_template_single_title(); 
             woocommerce_template_single_rating();
             woocommerce_template_single_price(); // this will output the price text
             woocommerce_template_single_excerpt(); // this will output the short description of your product.
             woocommerce_template_single_add_to_cart();
             woocommerce_template_single_meta();
             woocommerce_template_single_sharing();
?>

</div><!-- .summary -->

here all get single single you can set in your html

if you want to change breadcub then go to single-product file

follow below

comment

//do_action( 'woocommerce_before_main_content' );

this and

this two funcion

woocommerce_output_content_wrapper();
and
woocommerce_breadcrumb();

set it your ways




Monday 28 December 2015

Get near by Location using latitude and longitude from php and mysql in google map Kilometer

Get near by Location using latitude and longitude from php and mysql in google map Kilometer

To search by miles  instead of kilometers, replace 6371 with .3959

<?php


$username="root";
$password="";
$database="googlemap";



// Get parameters from URL
$center_lat = 23.036730;
$center_lng = 72.516373;
$radius = 6;


$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}

// Search the rows in the mstuser table
$query = sprintf("SELECT usermail, res_name, lat, lng, ( 6371  * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM mstuser HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",


  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));

  /*$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20",


  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));*/
$result = mysql_query($query);

$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}

header("Content-type: application/json");
$i=0;
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){


  $data[$i]['usermail'] = $row['usermail'];
  $data[$i]['res_name'] = $row['res_name'];
  $data[$i]['lng'] = $row['lng'];
  $data[$i]['lat'] = $row['lat'];
  $data[$i]['distance'] = $row['distance'];

  $i++;

}

echo json_encode($data);
?>

Sunday 27 December 2015

How Retrieve Latitude and Longitude via Google Maps API Using it's Address?

Hello

Retrieve Latitude and Longitude via Google Maps API Using it's Address

Here Sample code for Retrieve Latitude and Longitude via Google Maps API Using it's Address

check It can be Use full.


<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
      });
}
function address_lat_lag() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

      alert("Latitude: "+results[0].geometry.location.lat());
      alert("Longitude: "+results[0].geometry.location.lng());
 
  document.getElementById("lat").value = results[0].geometry.location.lat();
   document.getElementById("lag").value = results[0].geometry.location.lng();
      }

      else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
google.maps.event.addDomListener(window, 'load', initialize);

        </script>
    </head>
    <body>
        <input type="text" id="my-address">
        <button id="getCords" onClick="address_lat_lag();">getLat&Long</button>
       
        You can save here as textbox value
        <br/>
        <label>Latitude</label>
        <input type="text" id="lat"  name="lat"/>
         <label>Longitude</label>
        <input type="text" id="lag"  name="lag"/>
    </body>
</html>

Friday 18 December 2015

validation method added in jquery like selectbox validation,date formate(dd-mm-yyyy),price(decimal value),phone number,highlight error.

highlight error in jquery validation

validation method added in jquery like selectbox validation,date formate(dd-mm-yyyy),price(decimal value),phone number,highlight error.


selectbox value set option value 0 then set valueNotEquals:"0"
date formate set dateFormat: true and it validation of dd-mm-yyyy formate
price we can to set as decimal  float_number: true
phone if we want to set +91-10degits then set   indiaPhone: true

if you want no highlight you error then it can be added this method


        highlight: function(element) {
            $(element).css({
                "background-color": "rgba(60, 141, 188, 0.52)",
                "border-color": "red"
            });
        },
        unhighlight: function(element) {
            $(element).css({
                "background-color": "",
                "border-color": ""
            });
           
            here added on error color and border you can chanage here to highlight your textbox or any else input

 $('#test').validate({

        rules: {
            coupon_code: {
                required: true
            },
            price: {
                required: true,
                maxlength: 10,
                float_number: true
            },
            vendorname: {
                valueNotEquals: "0"
            },          
            startdate: {
                dateFormat: true
            },
             phone1: {
                indiaPhone: true,
                maxlength: 13
            },
            enddate: {
                dateFormat: true
            },
        },


        highlight: function(element) {
            $(element).css({
                "background-color": "rgba(60, 141, 188, 0.52)",
                "border-color": "red"
            });
        },
        unhighlight: function(element) {
            $(element).css({
                "background-color": "",
                "border-color": ""
            });
        }

    });




});


/** validation for Selectbox */


$.validator.addMethod("valueNotEquals", function(value, element, arg) {
    return arg != value;
}, "Please Select Value");



/** validation for Phone Number  in textbox */

$.validator.addMethod("indiaPhone", function(value, element, arg) {

    var filter = /^[0-9-+]+$/;
    var phone = filter.test(value)


    return arg = phone;


}, "Plese Enter Number");

/** validation for decimal value in textbox */

$.validator.addMethod("float_number", function(value, element, arg) {

    var filter = /^\d{0,8}(\.\d{1,2})?$/;
    var float_number = filter.test(value)


    return arg = float_number;


}, "please Enter Valid Number");


/** date validation for dd-mm-yyyy */

$.validator.addMethod("dateFormat",
    function(value, element, arg) {
        var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;

        var validate = dateformat.test(value);


        return arg = validate;

    },
    "Please Enter a date in the format dd-mm-yyyy.");

Monday 7 December 2015

Checked Checkbox Value Using Class In Jquey


Here Full Example

How TO Get All Checkbox value Using It's class

Checked Checkbox Value Using Class In Jquey


We can use on change event for every checkbox and getting value of it class.
use push to collect value check it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Checkbox Value Example</title>
</head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="application/javascript">
function getValueUsingClass(){
   /* declare an checkbox array */
   var chkArray = [];
  
   /* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
   $(".chk:checked").each(function() {
   chkArray.push($(this).val());
   });
  
   /* we join the array separated by the comma */
   var selected;
   selected = chkArray.join(',') + ",";
  
   /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
   if(selected.length > 1){
   alert("You have selected " + selected);
  
  
   }else{
   alert("Please at least one of the checkbox");
   }
   }
</script>
<body>
<input type="checkbox" class="chk" name="test" value="checked1" onchange="getValueUsingClass()"  />checked1
<input type="checkbox" class="chk" name="test" value="checked2"  onchange="getValueUsingClass()"  />checked2
<input type="checkbox" class="chk" name="test" value="checked3" onchange="getValueUsingClass()"  />checked3
<input type="checkbox" class="chk" name="test" value="checked4" onchange="getValueUsingClass()"  />checked4
<input type="checkbox" class="chk" name="test" value="checked5" onchange="getValueUsingClass()"  />checked5
<input type="checkbox" class="chk" name="test" value="checked6" onchange="getValueUsingClass()"  />checked6
<input type="checkbox" class="chk" name="test" value="checked7" onchange="getValueUsingClass()"  />checked7
</body>
</html>

Sunday 6 December 2015

How to Compare two strings using stored procedure in Mysql


 Compare two strings using stored procedure in Mysql
  1. Only need one (1) equals sign to evaluate
 DECLARE @tempo VARCHAR(20)
    SET @tempo = 'test'

IF @tempo = 'test'
  SELECT 'yes'
ELSE
  SELECT 'no'

return yes of this output

DECLARE @tempo VARCHAR(20)
    SET @tempo = 'test1'

IF @tempo = 'test'
  SELECT 'yes'
ELSE
  SELECT 'no'

return no in this output


you can also use interger  as value

set below type code for integer


 SET @temp = 1

IF @temp = 1
  SELECT 'yes'
ELSE
  SELECT 'no'
 
  return yes
 
 


IF @temp = 2
  SELECT 'yes'
ELSE
  SELECT 'no'
 
  return no