How to wipe all the tables and data in MySQL? Clean whole database

SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
  FROM information_schema.tables
  WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@tables,'dummy') INTO @tables;
 
SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;

Will not work via phpmyadmin or any script. this has to be run in cmd/terminal

Quick Command

wget https://gist.githubusercontent.com/harshvardhanmalpani/e670a8de7aa81673364dd48f125cb9ac/raw/ce04b319bf1594d148d3346e1474119fe1cd1b3f/flushdb.sql

mysql -hYOUR_DATABASE_HOSTNAME -uYOUR_DATABASE_USER -p YOUR_DATABASE_NAME < flushdb.sql

Source:
https://gist.github.com/harshvardhanmalpani/e670a8de7aa81673364dd48f125cb9ac

How to track qty changes in cart?

This is not CMS or software specific. Can be used for shopify, magento, wordpress or any other cart page

Assumption:
All the cart items have an input field for quantity in case they want to change qty for any item

Assumption:
All those input fields can be selected using queryselector. Either they have common name attribute or a common class.

Purpose:
We want to change class of update button to show that he has to press update button because quantities have been altered.

So lets get started:

js code:

$(document).ready(function($){
//please change query selector for qty inputs in line 3 and 5
    var ini_values = $("input[name='updates[]']").map(function(){return $(this).val();}).get();
    $(".quantity input").change(function(){
      let new_values = $("input[name='updates[]']").map(function(){return $(this).val();}).get();
      if(JSON.stringify(ini_values)!=JSON.stringify(new_values)) 
      { //change selector for update button
           $("#update-cart").addClass("pressme"); }
    else {
    $("#update-cart").removeClass("pressme");}
    });
  });

css code if needed

.pressme{background: white !important;
    border-color: #109ff6 !important;
  color: black !important;
  animation: blink 1s linear infinite;}
@keyframes blink{
0%{opacity: 0;}
50%{opacity: .5;}
100%{opacity: 1;}
}

Reference:

https://stackoverflow.com/a/24503913/2229148

How to add qty plus minus buttons in shopify?

Sorry this is not a detailed description but a summary with all code

Add available quantities first – as shown in this article – How to show stock quantities in all variants of shopify

^The above part is utmost necessary. because the following functions use previous js variables.

So here we go. Good Luck!!

javascript on the product page

<script>
  $(document).ready(function($){
       
    var  $j=new jQuery.noConflict();
    var qtyinput=$j("#quantity");
    var qtyplus=$j("#qtyplus");
    var maxallowed=parseInt($j(qtyinput).attr('max'));
    var qtyminus=$j("#qtyminus");
      var qtyvalue=parseInt($j(qtyinput).val());
    setTimeout(function(){$j(qtyminus).removeClass("hidden");
    $j(qtyplus).removeClass("hidden");
    },8000);
    $j(qtyminus).click(function($){
      qtyvalue=parseInt($j(qtyinput).val());
      maxallowed=parseInt($j(qtyinput).attr('max'));
      if(qtyvalue<2){checkFreeze(); return;}
       $j(qtyinput).val(qtyvalue-1);
                checkFreeze();    });
    $j(qtyplus).click(function($){
      qtyvalue=parseInt($j(qtyinput).val());
      maxallowed=parseInt($j(qtyinput).attr('max'));
      //    console.log(qtyvalue + " -- - -" + maxallowed);
      if(maxallowed<=qtyvalue){
        checkFreeze(); return;}
    $j(qtyinput).val(qtyvalue+1);
           checkFreeze();         });
  
  });
        </script>

html tags on product page. make sure you add these AROUND quantity input

<a id=qtyminus class="freeze fa fa-minus hidden"></a>
<input class="select-on-focus" min=1 type="text" size="3" id="quantity" name="quantity" value="1" {% if issingle %}max="{{ current_variant.inventory_quantity }}" {% endif; %}/>
<a id=qtyplus class="{% if current_variant.inventory_quantity==1 %}freeze {% endif; %}fa fa-plus hidden"></a>
              

javascript function inside your theme.js. Reason: so that this gets loaded aka defined before updateSku is called()

function checkFreeze(){
    $j=new jQuery.noConflict();
    var qtyinput=$j("#quantity");
    var qtyplus=$j("#qtyplus");
    var maxallowed=parseInt($j(qtyinput).attr('max'));
    var qtyminus=$j("#qtyminus");
      var qtyvalue=parseInt($j(qtyinput).val());
  //alert("max is "+maxallowed);
      if(maxallowed==0 || maxallowed===undefined){        
             $j(qtyplus,qtyminus).addClass("freeze");
        $j(qtyinput).val(0);
        return;
      }
  qtyvalue=parseInt($j(qtyinput).val());
      if(qtyvalue>=maxallowed){//newval=1;
        $j(qtyinput).val(maxallowed);
             $j(qtyplus).addClass("freeze");  
        }
      else{
        if(qtyvalue<1)
        $j(qtyinput).val(1);
      $j(qtyplus).removeClass("freeze");
      }
  qtyvalue=parseInt($j(qtyinput).val());
      if(qtyvalue>1){
        
      $j(qtyminus).removeClass("freeze");}
      else {
             $j(qtyminus).addClass("freeze");     
                  }
    };

changes in function updatesku. Add these lines inside the function. Make sure you have already followed part1

if(inv_qty[ variant.id ]!==undefined)$("#quantity").attr('max',inv_qty[ variant.id ]);
    else $("#quantity").attr('max',0);
    $(document).ready(function(){checkFreeze();});

After making changes as discussed in part1 and this article, the final updatesku function looks somewhat this


  _.updateSku = function(variant, $container){
    $container.find('.sku .sku__value').html( variant ? variant.sku : '' );
    $container.find('.sku').toggleClass('sku--no-sku', !variant || !variant.sku);
    if(inv_qty[ variant.id ] <1 || inv_qty[ variant.id ]==undefined)$("#stockstatus").html("<p class=bomb>Sold Out!</span></p>");
    else if(inv_qty[ variant.id ] <6)$("#stockstatus").html("<p class=fire>Hurry! Only <span class='variant-inventory'>"+ inv_qty[ variant.id ] + "</span> left in stock.</p>");
    else $("#stockstatus").html("<p class=grass><span class='variant-inventory'>"+ inv_qty[ variant.id ] + "</span> available in stock.</p>");
  if(inv_qty[ variant.id ]!==undefined)$("#quantity").attr('max',inv_qty[ variant.id ]);
    else $("#quantity").attr('max',0);
    $(document).ready(function(){checkFreeze();});
  }

CSS – can be added in custom.css

#qtydiv a{border: 1px solid #777;
    border-radius: 3px;
    font-size: 16px;
    padding: 0;
    line-height: 30px;
    width: 30px;
    background: #efefef;
    color: #444;
    height: 30px;
    vertical-align: baseline;
    text-align: center;
    cursor: pointer;
  margin:0 5px;}
#qtydiv a.freeze{cursor:not-allowed;
  border: 1px solid #eee;
    color: #bcbcbc;}

Sort keys of an array based on order of values in another array – PHP

$a=array(56,7,6,8,5,34);
$b=array(
array(6,"34er34",44),
array(8,"34d34",44),
array(7,"343th4",44),
array(34,"343d4",44),
array(56,"3434",44),
array(5,"343gh4",44));
$d=array_column($b,0);
var_dump($d);
$g=[];
foreach($a as $c)
{
  $f=array_search($c,$d);
  if($f!==false)
      $g[]=$b[$f];
 }
var_export($g);

How to filter and validate pincode in Indian woocommerce?

By default, Woocommerce only validates ZIP code of few countries only. Woocommerce stores in India, are thus invalidated in case of PINCODE inputs from customers. Here is how you can enable checking of pincode for India woocommerce:

Put the following code in your custom function file or child theme functions.php

add_filter('woocommerce_validate_postcode','validate_indian_postcode',10,3);

function validate_indian_postcode($valid, $postcode, $country){
	if($country=="IN")
			$valid = (bool) preg_match( '/^([0-9]{6})$/', $postcode );
  // checks your $postcode, if valid $valid will be true because of preg_match else false
  return $valid;
}

Reference:

https://github.com/woocommerce/woocommerce/blob/ef0f527b40dba539e982efff26211fa577a24cf9/includes/class-wc-validation.php#L44

How to show stock quantity for all variants in shopify?

How to show “xxx left in stock” on shopify product page?

Shopify – show ONLY XX AVAILABLE IN STOCK on product page

Start by adding snippet in product-template.liquid

 <div id="stockstatus">
        {% if product.variants.size < 2 %}
          {% assign current_variant= product.variants.first %}
        {% endif %}
        {% if current_variant.inventory_quantity < 1 %}
            <p class="zero">Sold Out!<span class="variant-inventory">{{ current_variant.inventory_quantity }}</span></p>
        {% elsif current_variant.inventory_quantity < 6 %}
            <p class="few">Hurry! Only <span class="variant-inventory">{{ current_variant.inventory_quantity }}</span> left in stock.</p>
        {% else %}
            <p class="plenty"><span class="variant-inventory">{{ current_variant.inventory_quantity }}</span> available in stock.</p>
        {% endif %}
 </div>
<script>
     var inv_qty = {};
     {% for var in product.variants %}
           inv_qty[{{- var.id -}}] = {{ var.inventory_quantity | default: 0 }};
     {% endfor %}
</script>

Now in theme.js or theme.js.liquid and edit function updateSku / _.updateSku

if(inv_qty[ variant.id ] <1 || inv_qty[ variant.id ]==undefined)$("#stockstatus").html("<p class=zero>Sold Out!</span></p>");
    else if(inv_qty[ variant.id ] <6)$("#stockstatus").html("<p class=few>Hurry! Only <span class='variant-inventory'>"+ inv_qty[ variant.id ] + "</span> left in stock.</p>");
    else $("#stockstatus").html("<p class=plenty><span class='variant-inventory'>"+ inv_qty[ variant.id ] + "</span> available in stock.</p>");
  

Now add some CSS in custom.css or styles.css

p.zero,p.few,p.plenty{background: #b2e7b2;
    display: inline-block;
    padding: 3px 10px;}
p.few:before {
    content: "\f0e7";
    font-family: "FontAwesome";
    margin-right: 10px;}
p.zero:before {
    content: "\f119";
    font-family: "FontAwesome";
    margin-right: 10px;}
p.few,p.zero{color: #fff;background: #eb5050 !important;}

Also note, you can add css for the qty number by using selector

.variant-inventory{font-weight:bold}
or more specifically
#stockstatus .variant-inventory{font-weight:bold}

Hopefully it would work on your theme

Extend this functionality to show quantity plus minus buttons also

References:

https://community.shopify.com/c/Shopify-Design/Showing-the-stock-quantity-per-variant/m-p/428953/highlight/true#M111057

https://community.shopify.com/c/Shopify-Design/How-do-I-Show-inventory-quantities-on-product-pages-using-Debut/m-p/330715/highlight/true#M86371

https://community.shopify.com/c/Shopify-Design/See-if-a-product-has-variants/m-p/414669/highlight/true#M107631

What is DMARC and How to set it up?

DMARC stands for Domain-based Message Authentication, Reporting, and Conformance

It can be used as a way to prevent specific type of SPAM. Hence it should be added as TXT record in your DNS zone, just like SPF and DKIM signatures.

Example DMARC policies

These are some example policies and how they appear in the DNS TXT record.

TXT record hostname must be “_dmarc

The values in these examples are defined in DMARC TXT record values, below.

Actions to take for failed DMARC checkTXT record contents
Take no action on messages that fail the DMARC check. Email a daily report to [email protected]v=DMARC1; p=none; rua=mailto:[email protected]
Put 5% of the messages that fail the DMARC check in recipients’ spam folders. Email a daily report to [email protected]v=DMARC1; p=quarantine; pct=5; rua=mailto:[email protected]
Reject 100% of messages that fail the DMARC check. Email a daily report to two addresses: [email protected] and [email protected]. Failed messages cause an SMTP bounce to the sender.v=DMARC1; p=reject; rua=mailto:[email protected], mailto:[email protected]

Further Reading:

https://support.google.com/a/answer/2466580

https://support.google.com/a/answer/2466563?hl=en&ref_topic=2759254

Funny php bug due to hashing and is_numeric

So I was working on an automation project and was testing the api to upload entitites.

I used get parameters to send data and wrote a wrapper on server to process that. I used hashes (part of hashes to be precise) to identify the requester instead of using real names.

some name came up with hash

12200e7973d0eecd8d75da83e816783496e440e22210ee72cb5cf37f7989a8ff

I was using first 10 characters of this has which happen to be

12200e7973

If you notice, only alphabet is “e” and all others are digits.
But at the same time this is a number in scientific notation
just the way 1e3 is 1000 because of exponentiation involved. My partial hash string was also being converted and was close to infinity.

My api at the backend was checking the given parameter with is_numeric and in this case, my parameter “12200e7973is 100% numeric (EVEN IF I WAS STORING IT AS A STRING).
Hence my script was failing to save correct data and a major column was left empty in the tables.

This was another blunder by me at programming, but you can easily fix it if you use is_int instead of is_numeric because it would fail type checking via is_int.

Of course I had to edit some code with explicit type casting for other types of api calls which were using IDs instead of hashes to identify the users.

Example code: (This is Not the exact code, not recommended for production usage)

// API ENDPOINT
$user=isset($_REQUEST['user']) ?? $_REQUEST['user'] : 1;
// calling the function with string $user
abc ("xyz",$user);
// Normal code:
$user=$this->getLoggedInUser();
$userid=(int)$user; //explicit casting
//calling the same function with int val
abc("mnop",$userid);

How to reverse the ids in a mysql table column without breaking primary key constraint?

Let me explain the problem scenario: Let us assume we have a table with 4 columns in it out of which 1 is PRIMARY column and rest 3 contain some data.

What we want to do is to reverse the primary key IDs for that data keeping the rest of data intact. It is like shifting the first row to end and moving last row to starting.

Initial Data

idnameemailanything
1jacobwhateverhow to reverse
3nathanwhosoeverisnathanids in mysql table column
4jagmohanidontknowjagmohanwithout breaking
8monicaiamsexyprimary key constraint
9batmanidontexistinrealworldi am batman

Data after update

idnameemailanything
9jacobwhatever how to reverse
8nathanwhosoeverisnathan ids in mysql table column
4jagmohanidontknowjagmohan without breaking
3monicaiamsexy primary key constraint
1batman idontexistinrealworld i am batman

Dude, you are just reversing the column, what is so tough in this?

So, this seems simple to reverse an array if isolated by key “id“. But you have to understand that this column is the primary key. So if you run a command to change id for “jacob” to “9“. It will give you error: “Duplicate entry for id 9

So here is my proposed solution, I start with pair of first and last row and then swap them. Then swap second and second last row. and So on…

If total rows are odd, we will be left with 1 row which does not need correction because it will already be the middle row.

If total rows are even, we would swap middle two rows too.

Here is my solution in PHP

$possible_group_id="3";
$ai=12720; //can be any high int which does not exist in column `id` yet
$q="select id,email from table_name where `possible_group_id`=$possible_group_id order by id asc";
$r=mysqli_query($f,$q);
$row_collection=[];
$ct=[];
while($row=mysqli_fetch_row($r))
{
    $row_collection[]=$row;
    $ct[]=$row[0];
}
$pt=array_reverse($ct);
$size=count($row_collection);
for($i=0;$i<$size;$i++)
{
    $row_collection[$i][2]=$pt[$i];
}
echo "start transaction;<br>";
foreach($row_collection as $k=>$v)
{    
    if($k < floor($size/2)){
    echo 'UPDATE `table_name` SET `id`='.$ai.' WHERE `email`="'.$row_collection[$size-$k-1][1].'";<br>';
    echo 'UPDATE `table_name` SET `id`='.$v[2].' WHERE `email`="'.$v[1].'";<br>';
    echo 'UPDATE `table_name` SET `id`='.$row_collection[$k][0].' WHERE `email`="'.$row_collection[$size-$k-1][1].'";<br>';}
    else break;
}
echo "commit;<br>";

It would output this:

start transaction;
UPDATE `table_name` SET `id`=12720 WHERE `email`="idontexistinrealworld ";
UPDATE `table_name` SET `id`=9 WHERE `email`="whatever";
UPDATE `table_name` SET `id`=1 WHERE `email`="idontexistinrealworld ";
UPDATE `table_name` SET `id`=12720 WHERE `email`="iamsexy";
UPDATE `table_name` SET `id`=8 WHERE `email`="whosoeverisnathan";
UPDATE `table_name` SET `id`=3 WHERE `email`="iamsexy";
commit;

How to remove sign in popup from Magento 2 checkout page?

Magento2 has this authentication pop up on checkout page, which many store owners wont like to see on their checkout page.

Background of this pop up area and Related files

The pop up itself is generated by Magento_Customer::account/authentication-popup.phtml

But this pop up works very differently on checkout page. In fact this is a separate pop up than the one you see in header area. It is embedded in a series of js files which are governed by knockout-js

Other file responsible is: vendor/magento/module-checkout/view/frontend/web/js/proceed-to-checkout.js

Here is how to remove it finally

Edit file or overload the file

app/design/frontend/YourVendor/YourTheme/Magento_Checkout/web/template/onepage.html

delete the following lines and save the file

<!-- ko foreach: getRegion('authentication') -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->

Reference:

https://github.com/magento/magento2/blob/2.2/app/code/Magento/Checkout/view/frontend/web/template/onepage.html

https://github.com/magento/magento2/blob/fc66fe443d87c4e69fe9022d7c95fe66e0565978/app/code/Magento/Checkout/view/frontend/layout/checkout_index_index.xml#L39