SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry Magento 2

SELECT u.value_id,u2.value_id, u.attribute_id, u.entity_id, u.value
FROM catalog_product_entity_int u, catalog_product_entity_int u2
WHERE u.entity_id = u2.entity_id AND u.attribute_id = u2.attribute_id AND u.value= u2.value and u.value_id<u2.value_id

DELETE FROM catalog_product_entity_int
WHERE value_id IN (
    SELECT u.value_id as value_id
FROM catalog_product_entity_int u, catalog_product_entity_int u2
WHERE u.entity_id = u2.entity_id AND u.attribute_id = u2.attribute_id AND u.value= u2.value and u.store_id=u2.store_id and u.value_id<u2.value_id

[SOLVED] Magento 2 Error: A technical problem with the server created an error. Try again to continue what you were doing. If the problem persists, try again later.

Sometimes debugging on Magento can be annoying, specially if something just arises out of the blue, not while you are actually writing a code.

Magento Error - Technical Problem with server
If Problem Persists, try again later

This is something that occurs on Magento admin panel. As of now, it can be one out of 3 reasons, let us discuss them:

1. Admin Password

Try to change admin password, log out and log in again. This should fix it.

2. Some un compiled code or pending schema change

upgrade, compile, deploy, reindex, clean cache

rm -rf generated/* var/cache/* var/view_preprocessed/*
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento indexer:reindex
php bin/magento cache:clean

3. Check for some extra output in the php files

See Line 41
One of the developers left this in index.php and this was just messing with the api calls from admin panel because it was corrupting json output.

Magento 2 : How to fix tablespace for table exists | base table or view already exists

Fixing General error: 1813 Tablespace for table xx Please DISCARD the tablespace before IMPORT and SQLSTATE[42S01]: Base table or view already exists

Recently I encountered this error while upgrading an extension on Magento 2.2.2
The error was

SQLSTATE[HY000]: General error: 1813 Tablespace for table '`jack_db1`.`jill_table`' exists. Please DISCARD the tablespace before IMPORT., query was: CREATE TABLE IF NOT EXISTS `jill_table`

When I tried to fix the above error, I received:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table '`jack_db1`.`jill_table`' already exists, query was: CREATE TABLE IF NOT EXISTS `jill_table`

So here is how to fix it:

Important Note: Replace jack_db1 with your database Name and jill_table with your table Name

PART 1 – Fixing MySQL backend

First log in to server and check the mysql data folder (mine was /var/lib/mysql/jack_db1)
say your database name is jack_db1 and your table is jill_table
so issue

ls /var/lib/mysql/jack_db1

You will find .frm and .idb files
Note that these files are present as a couple (each frm file has a corresponding idb file)
But the table that is causing you issues will have one of them missing.
.frm was missing in my case, so copy any other frm file and name it as jill_table.frm (i copied wishlist.frm using following command )
cd /var/lib/mysql/jack_db1;cp wishlist.frm jill_table.frm
use the following command to fix ownership

chown -R mysql:mysql /var/lib/mysql/jack_db1/*

Part 2: Fixing Magento Backend

Login to phpMyAdmin if available or use MySQL CLI to perform the following actions.
In the table setup_module of your magento installation
Delete the row which is related to your corrupted extension

DELETE FROM `setup_module` WHERE module="Custom_Module"

you can also do the same from phpMyAdmin

Now delete the table which was causing the issue, (you would not be able to view the table in phpmMyAdmin)
Just run the following query in SQL

DROP TABLE IF EXISTS `jill_table`;

Part 3: Upgrade the Magento using php cli

run the following commands:

rm -rf var/cache/*
rm -rf generated/*
php bin/magento module:enable Custom_Module --clear-static-content
php bin/magento setup:upgrade
#  Hopefully this time you wont see any errors, proceed as usual if upgrade command worked.
#  run
php bin/magento setup:di:compile
#  and 
php bin/magento setup:static-content:deploy -f

Good Luck with Magento 🙂

Remove sku column from Magento 2 invoice and pdf

Edit the file

Inside function draw(), remove/comment following code:

   // draw SKU
        $lines[0][] = [
            'text' => $this->string->split($this->getSku($item), 17),
            'feed' => 290,
            'align' => 'right',

To remove the SKU header in table header, edit the file

//$lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];

and copy the file vendor/magento/module-sales/view/frontend/templates/email/items/order/default.phtml
to app/design/your/theme/Magento_Sales/templates/email/items/order/default.phtml
and remove the code

<p class="sku"><?= /* @escapeNotVerified */  __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p>

Magento 2 temporary fix for Alphabetical sorting of Configurable product options

Just re-write the file vendor/magento/module-configurable-product/Model/ConfigurableAttributeData.php

* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
namespace Magento\ConfigurableProduct\Model;
use Magento\Catalog\Model\Product;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute;
* Class ConfigurableAttributeData
* @api
* @since 100.0.2
class ConfigurableAttributeData
* Get product attributes
* @param Product $product
* @param array $options
* @return array
public function getAttributesData(Product $product, array $options = [])
$defaultValues = [];
$attributes = [];
foreach ($product->getTypeInstance()->getConfigurableAttributes($product) as $attribute) {
$attributeOptionsData = $this->getAttributeOptionsData($attribute, $options);
if ($attributeOptionsData) {
$productAttribute = $attribute->getProductAttribute();
$attributeId = $productAttribute->getId();
$attributes[$attributeId] = [
'id' => $attributeId,
'code' => $productAttribute->getAttributeCode(),
'label' => $productAttribute->getStoreLabel($product->getStoreId()),
'options' => $attributeOptionsData,
'position' => $attribute->getPosition(),
$defaultValues[$attributeId] = $this->getAttributeConfigValue($attributeId, $product);
return [
'attributes' => $attributes,
'defaultValues' => $defaultValues,
public function labelsort($a,$b){ return strcmp($a['label'], $b['label']);}
* @param Attribute $attribute
* @param array $config
* @return array
protected function getAttributeOptionsData($attribute, $config)
$attributeOptionsData = [];
foreach ($attribute->getOptions() as $attributeOption) {
$optionId = $attributeOption['value_index'];
$attributeOptionsData[] = [
'id' => $optionId,
'label' => $attributeOption['label'],
'products' => isset($config[$attribute->getAttributeId()][$optionId])
? $config[$attribute->getAttributeId()][$optionId]
: [],
if(count($attributeOptionsData) > 1){usort($attributeOptionsData,array($this,'labelsort'));}
return $attributeOptionsData;
* @param int $attributeId
* @param Product $product
* @return mixed|null
protected function getAttributeConfigValue($attributeId, $product)
return $product->hasPreconfiguredValues()
? $product->getPreconfiguredValues()->getData('super_attribute/' . $attributeId)
: null;

How to add custom attributes in Magento 2 product CSV export

Core Method is to edit the file

and Edit the variable $_exportMainAttrCodes

Add your attributes in the array like “custom1″,”custom2”, etc and save the file.

Next time you export the csv, you will see new columns in the file.

Insert Indian States in Magento Database

Connect to your server’s database using mysql cli or phpmyadmin and use the following query

INSERT INTO `directory_country_region` VALUES 
(NULL,"IN","AP","Andhra Pradesh"),
(NULL,"IN","AR","Arunachal Pradesh"),
(NULL,"IN","HP","Himachal Pradesh"),
(NULL,"IN","JK","Jammu and Kashmir"),
(NULL,"IN","MP","Madhya Pradesh"),
(NULL,"IN","TN","Tamil Nadu"),
(NULL,"IN","UP","Uttar Pradesh"),
(NULL,"IN","WB","West Bengal"),
(NULL,"IN","AN","Andaman and Nicobar Islands"),
(NULL,"IN","DH","Dadra and Nagar Haveli"),
(NULL,"IN","DD","Daman and Diu"),

How to create Magento 2 category programmatically?

Use this code:

use \Magento\Framework\App\Bootstrap;
echo 'code by harshvardhanmalpani';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
function createCategory($a='',$b=2,$c=true,$d='',$e='',$f='',$g='') {
global $objectManager;
$category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();
$category->setParentId($b); // 1: root category.
'description' => $d,
'meta_title' => $e,
'meta_keywords' => $f,
'meta_description' => $g,
createCategory("Xyz",4,false,"description","m title");

How to secure a folder by whitelisting one IP using HTACCESS and denying all others

The process involves matching all requests for an IP, if the IP does not match redirect all secured directory requests.

RewriteCond %{REMOTE_ADDR} !^120\.120\.120\.120
RewriteRule ^admin/.* - [L,R=403] 
RewriteCond %{REMOTE_ADDR} ^120\.120\.120\.120
RewriteRule ^admin$ - [L,R=403]

If you want to control this IP using a script, you can add 2 lines

# your rules will appear here using php script

Now add a script, say happy.php
and use the following code:

$htaccess = file_get_contents('.htaccess');
$ip= str_replace(".","\.",$_SERVER['REMOTE_ADDR']);
$rules="RewriteCond %{REMOTE_ADDR} !^".$ip."
RewriteRule ^admin/.* - [L,R=403]
RewriteCond %{REMOTE_ADDR} !^".$ip."
RewriteRule ^admin$ - [L,R=403]";
$problem="###CUSTOM RULES###\r\n".$rules.
"\r\n###CUSTOM RULES###";
#please copy the next line carefully, no extra spaces or new lines
$solution=preg_replace('/###CUSTOM RULES###.*?###CUSTOM RULES###/sm',$problem,$htaccess);
file_put_contents('.htaccess', $solution);

you can also specify your error page for specific http code: 403
ErrorDocument 403 /er.htm

Start a magento instance programmatically

This Code:

$mageFilename = 'app/Mage.php';
require_once $mageFilename;
ini_set('display_errors', 1);
error_reporting(E_ALL &amp; ~E_NOTICE);
Mage::register('isSecureArea', 1);
//your mage code here