Monday 16 November 2015

how to remove index and unique constraint in mysql

Hello

here Example of remove how to remove index and unique constraint in mysql

first check table how many constraint  in table after you can remove.

here the query for show index in table

SHOW INDEX FROM Your-table-Name

after remove all index name display in column

here the query

ALTER TABLE Your-table-Name DROP INDEX Your-field-unique-constraint -name;

Please check this 

Login With Facebook Using javascript SDK Example

Hello

Here Example of Facebook Login With Javascript SDK
the login flow step-by-step and explain each step clearly - this will help you if you are trying to integrate Facebook Login into an existing login system, or just to integrate it with any server-side code you're running. But before we do that, it's worth showing how little code is required to implement login in a web application using the JavaScript SDK.

Create Login.php File

Code For Login.php

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function facebook_login (){
    if(typeof(FB) == "undefined") {
        alert("Facebook SDK not yet loaded please wait.")
      }
    FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        console.log('Logged in.');
        basicAPIRequest();

      }
      else {
       FB.login(function(response) {
 
      if (response.status === 'connected') {
        console.log('Logged in.');
        basicAPIRequest();
  }
 
}, {scope: 'email,user_birthday,user_location,public_profile,publish_actions'});

      }
    });    
}

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'your-app-id',
      xfbml      : true,
   status     : true, // check login status
      version    : 'v2.0'
    });

FB.Event.subscribe('auth.login', function () {
         basicAPIRequest()
      });

  };

 
  

  
  
   (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));


function basicAPIRequest() {
    FB.api('/me',
        {fields: "id,about,age_range,picture,bio,birthday,context,email,first_name,gender,hometown,link,location,middle_name,name,timezone,website,work"},
        function(response) {
         console.log('API response', response);
         /*  $("#fb-profile-picture").append('<img src="' + response.picture.data.url + '"> ');
          $("#name").append(response.name);
          $("#user-id").append(response.id);
          $("#work").append(response.gender);
          $("#birthday").append(response.birthday);
          $("#education").append(response.hometown);
  $("#email").append(response.email);*/
 

 
  $.ajax({
  url: "facebook_login_query.php",
  data: {
  email:response.email,
  birthday : response.birthday,
  gender : response.gender
  },
  success: function( response ) {
alert(response);
window.location.href = "http://localhost/home.php";
return false;
 
  }
 

});
 
        }
    );
  }



</script>
<!--<div  class="fb-login-button" data-scope="email,user_birthday,user_hometown,user_location,user_website,user_work_history,user_about_me
" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="true"  >
</div>
</div> -->


<button id='load' onClick="facebook_login();">Load data</button>
</html>

Create facebook_login_query.php

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


 echo $uname = $_GET['email'];


if(!is_null){
echo $newbirthday = $_GET['birthday'];
echo $birthday = date("Y-m-d", strtotime($newbirthday));

}else{
$birthday= '';
}
echo $gender = strtolower($_GET['gender']);



   $select="select * from mstuser where username='$uname' and facebook_login='1' and  isActive = '1' AND isDelete = '0'";
$result=mysql_query($select);

  $total_result = mysql_num_rows($result);
if($total_result == 1){

$row = mysql_fetch_assoc($result);
  $_SESSION['vid']=$row['id'];
$_SESSION['username'] = $row['username'];
  $roleid = $row['roleid'];
$count=mysql_num_rows($result);


}else{
echo "insert into mstuser set username='$uname',facebook_login='1',isActive = '1',isDelete = '0' ";
  $insert_mstuser = mysql_query("insert into mstuser set username='$uname',facebook_login='1',isActive = '1',isDelete = '0' ");



  $select="select * from mstuser where username='$uname' and facebook_login='1' and  isActive = '1' AND isDelete = '0'";
$result=mysql_query($select);
$row = mysql_fetch_assoc($result);
  $_SESSION['vid']=$row['id'];
  $roleid = $row['roleid'];
$_SESSION['username'] = $row['username'];
$count=mysql_num_rows($result);



}
?>

Create Home.php

echo "Welcome user";

Tuesday 3 November 2015

Get Country State and City using JavaScript ajax and php

Hello

Here Example Of set your country,state,city using javascript ajax and php

Country State City Dropdown Using Ajax. ... In the onChage event of the country drop down we have called showhint() function of the javascript and also get current state of city using show_city();

Full Code

--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `id` int(11) NOT NULL auto_increment,
  `cid` int(11) NOT NULL,
  `sid` int(11) NOT NULL,
  `city_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`id`, `cid`, `sid`, `city_name`) VALUES
(1, 1, 1, 'ahmedabad'),
(2, 1, 1, 'rajkot'),
(3, 2, 3, 'afarica city 1'),
(4, 2, 4, 'afarica city 2');

-- --------------------------------------------------------

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `id` int(11) NOT NULL auto_increment,
  `countryname` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`id`, `countryname`) VALUES
(1, 'india'),
(2, 'africa');

-- --------------------------------------------------------

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `id` int(11) NOT NULL auto_increment,
  `cid` int(11) NOT NULL,
  `s_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`id`, `cid`, `s_name`) VALUES
(1, 1, 'gujrat'),
(2, 1, 'bihar'),
(3, 2, 'afarica state1'),
(4, 2, 'afarica state 2');

all_date.php file

<script>
function showHint(str) {

    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {


                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "getstate.php?q=" + str, true);
        xmlhttp.send();
    }

}

function showCity(str) {


    if (str.length == 0) {
        document.getElementById("txtCity").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {


                document.getElementById("txtCity").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "getcity.php?q=" + str, true);
        xmlhttp.send();
    }

}

</script>

<?php

mysql_connect("localhost","root","");

mysql_select_db('test_country');

$get_country = mysql_query("select * from country");



?>
<label> country</label>

<select name="country" onchange="showHint(this.value)" >
<option value="0" >select country</option>
<?php
while($row_country = mysql_fetch_assoc($get_country)){ ?>


<option value="<?php echo $row_country['id']; ?>"/>
<?php echo $row_country['countryname'];  ?>
</option>


<?php
}
?>
</select>
<select name="state" id="txtHint" onchange="showCity(this.value)" >
</select>

<select name="city" id="txtCity">
</select>
</br>

getstate.php file

<option value="0" >select state</option>
<?php
mysql_connect("localhost","root","");

mysql_select_db('test_country');

$q=$_GET['q'];

echo $select_state= mysql_query("select * from state where cid=".$q);

while($result_state= mysql_fetch_array($select_state)){ ?>

<option value="<?php echo $result_state['id']; ?>"><?php echo $result_state['s_name']; ?></option>

<?php }
?>

getcity.php file

<option value="0" >select City</option>
<?php
mysql_connect("localhost","root","");

mysql_select_db('test_country');

$q=$_GET['q'];

echo $select_state= mysql_query("select * from city where sid=".$q);

while($result_state= mysql_fetch_array($select_state)){ ?>

<option value="<?php echo $result_state['id']; ?>"><?php echo $result_state['city_name']; ?></option>

<?php }
?>

Monday 2 November 2015

How to Get Difference Between Two date in php

Hello,

Here Example of get difference between two dates in year,month and days.

You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods.

<?php

$date1 = "2014-03-24";
$date2 = "2015-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));




echo "Get Your Year diffrernce:-".$years."year";
echo "<br/>";
echo "Get Your Year diffrernce:-".$months."months";
echo "<br/>";
echo "Get Your Year diffrernce:-".$days."days";

Tuesday 29 September 2015

Show Categories Which Are not Included in Navigation Menu in Magento

Hello,

Get categories list which are not include in Navigation in magento.

Some time you want that are not added in navigation but categories active and you want to
get or listing.

<ul class="full_category">
<?php $_categories = Mage::getResourceModel('catalog/category_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('is_active', 1) //only active categories
    ->addAttributeToFilter('include_in_menu', 0)
    ->addAttributeToSort('position');//sort by position

foreach ($_categories as $_category) { ?>
<li class="cat">
                       
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>" title="<?php echo $_category->getName() ?>"><strong class="strongsm"><?php echo $_category->getName() ?></strong></a>
                           
</li>
<?php }?>
</ul>

Monday 28 September 2015

Get All Cms Page in magento

Hello,

Some Time You need to add Cms page in your site map. you need your page page link and name.
I have same issue. I getting for query and use it's working. you can try it.

Get all Cms Page in Magento

$storeId = $this->helper('core')->getStoreId(); // thanks to drawandcode for this
$cms = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('is_active',1)
->addFieldToFilter('identifier',array(array('nin' => array('no-route','enable-cookies'))))
->addStoreFilter($storeId);
$url = Mage::getBaseUrl();
$html = "";
foreach($cms as $cmspage):
$page = $cmspage->getData();
if($page['identifier'] == "home"){
echo  "<li><a href=\"$url\" title=\"".$page['title']."\">".$page['title']."</a></li>\n";
} else {
echo "<li><a href=\"$url".$page['identifier']."\" title=\"".$page['title']."\">".$page['title']."</a></li>\n";
}
endforeach;

include , require and require_once , include_once in php

 include , require and require_once , include_once in php 


include, require and require_once,include_once are used to include a file into the PHP code

for example of include and require

<h1>Welcome to My blog!</h1>
<?php include 'header.php';
?>

it can added file in php code.

in require example

<h1>Welcome to My blog!</h1>
<?php require 'header.php';
?>

difference between  include and require

 when a file is included with the include statement and PHP cannot find it, the script will continue to execute

and

the echo statement will not be executed because the script execution dies after the require statement returned a fatal error

include_once 

It can be used include a PHP file another one, it can used to add files once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

Syntax



include_once('name of the called file with path');

example 

<?php include_once('xyz.php'); 

?>

same as require_once used.

<?php require_once('example.php')  ?>

include_once and require_once same different with include and require.




Difference between Echo And Print In Php

Hello,

Here I can Give both of use echo and print in php. I give example and use.

Echo and Print are almost same. they are both output on screen. they are used with and without
parentheses.

Difference Echo And Print



  1. print return value and echo not return value.
  2. echo faster than print.
  3.  echo without parentheses can take multiple parameters, which get concatenated but print give error.

How Can Use.



$data = "hello".
$data1 ="jaydip";

echo "<h2>My echo information</h2>";
echo "namste !<br>";

echo $data."".$data1;


echo without parentheses can take multiple parameters 
echo "jj","123",1,3;

same like in Print:

$data = "hello".
$data1 ="jaydip";

print "<h2>My echo information</h2>";
print "namste !<br>";

print $data."".$data1;

you can use as print in 
$test=1;
($test==2) ? print "true" : print "false";


Thursday 24 September 2015

Filtering a Magento product collection by multiple categories and Stock item and filter current product in product detail page

Hello,

I  Want to create section to get same product of different categories of products with Stock or quantity.

after i want get product of minimum of product quantity 50%.

for that i will join 'cataloginventory/stock_item', and  'catalog/category_product'  get this collection.

this section create in product detail page that why i am filter current product using it product id.

Please Below Code it help to you.

$product_id = Mage::registry('current_product')->getId();
    $category_ids = $_product->getCategoryIds();
$collection = Mage::getModel('catalog/product')->getCollection()
 ->addAttributeToSelect('*')
 ->addAttributeToFilter('entity_id', array('neq' => $product_id))
 ->addAttributeToFilter('status', 1)
 ->addStoreFilter();
$conditions = array();
foreach ($category_ids as $categoryId) {
 if (is_numeric($categoryId)) {
   
  $conditions[] = "{{table}}.category_id = $categoryId";
 }
}
$collection->distinct(true)
->joinField('category_id', 'catalog/category_product', null, 'product_id = entity_id', implode(" OR ", $conditions), 'inner');
$collection->joinField(
    'qty',
    'cataloginventory/stock_item',
    'qty',
    'product_id=entity_id',
    '{{table}}.stock_id=1',
    'left'
);
 foreach ($collection as $_item) {
   
    //echo $_item->getName()."</br>";
     $product_qty = $_item->getQty();
     $product_qty = round($product_qty);
    $product_qty = $product_qty/100;
    if($product_qty >= 0.5){
       
        echo $_item->getName()."</br>";
       
        }
       
 }

Please Below code it help getting products.

Thursday 17 September 2015

Price LessThan 1000 Get Products in Magento

Hello,

Here I am Create Custom Query for Product list. I want to get all product that price
less than 1000 in magento. I am Giving Example for that

First Create Cms page goto Cms=>page

in cms page
goto design=>Layout Update XML

Write below code in xml

<reference name="root">
<action method="setTemplate"><template>page/2columns-left.phtml</template></action>
 <action method="unsetChild"><alias>breadcrumbs</alias></action>    
    <block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs">
        <action method="addCrumb">
            <crumbName>Home</crumbName>
            <crumbInfo><label>Home</label><title>Home</title><link>/</link></crumbInfo>
        </action>
        <action method="addCrumb">
            <crumbName>Custom Page</crumbName>
            <crumbInfo><label>1000 Under</label><title>1000 Under</title></crumbInfo>
        </action>      
    </block>
</reference>

<reference name="left">
     <block type="catalog/navigation" name="catalog.categorymenu" before="catalog.leftnav" template="catalog/product/categorymenu.phtml"/>

        </reference>
<reference name="content">
<block type="catalog/product_new" name="product_list" template="catalog/product/list.phtml">
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
</block>
<action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
</block>
</reference>

after create block in your app\code\local\Mage\Catalog\Block\Product\new.php

Write this code for that

<?php

class Mage_Catalog_Block_Product_New extends Mage_Catalog_Block_Product_List 
   function get_prod_count() 
   { 
      //unset any saved limits 
      Mage::getSingleton('catalog/session')->unsLimitPage(); 
      return (isset($_REQUEST['limit'])) ? intval($_REQUEST['limit']) : 12;//set your page limit 
   }// get_prod_count 

   function get_cur_page() 
   { 
      return (isset($_REQUEST['p'])) ? intval($_REQUEST['p']) : 1; 
   }// get_cur_page 

   /** 
    * Retrieve loaded category collection 
    * 
    * @return Mage_Eav_Model_Entity_Collection_Abstract 
   **/ 
   protected function _getProductCollection() 
   { 
      

      $collection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSelect('*')
                        ->addPriceData()
                        ->setOrder('price', 'ASC')
                        ->addAttributeToFilter('price', array('lt' => '1001'))
                        ->addFieldToFilter('status', array('eq' => '1')
                    );

      $this->setProductCollection($collection); 

      return $collection; 
   }// _getProductCollection 
}// Mage_Catalog_Block_Product_New 

?>