If you want to delete legacy database table then you can follow this blog. In blog, We try to delete database entries using root script in magento2.
Here is script for delete entries from magento database.
Create file deleteData.php
in magento root directory.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('global');
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$table = $resource->getTableName('table_name');
$sql = "delete from $table LIMIT 10000;";
$connection->query($sql);
$data = $connection->fetchAll("select count(*) as total_record from $table");
print_r($data);
die();
You can run script in magento root path on server.
php deleteData.php
You can use php $argv
for pass parameters while run script. See document
Here is code you delete entries with parameter command.
Command php deleteData.php query_limit_number loop_count
First parameter is for mysql limit number and second params for how much time this query will run.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require '../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('global');
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$table = $resource->getTableName('table_name');
$num = isset($argv[1])? $argv[1] : 100000;
$i = isset($argv[2])? $argv[2] : 1 ;
for ($i; $i > 0 ; --$i) {
$sql = "delete from $table LIMIT $num;";
echo $sql."\n";
$connection->query($sql);
#echo "Wait for 5 seconds \n";
#sleep(5); #use sleep function so database has normal load
}
$data = $connection->fetchAll("select count(*) as total_record from $table");
print_r($data);
die();
Run below command for query_limit_number = 10000
and loop_count = 10
php deleteData.php 10000 10 #php deleteData.php query_limit_number loop_count
I hope this blog is useful for create root script in magento2 for delete database entries. In case, I missed anything or need to add some more information, Don’t heisted to leave a comment in this blog, I’ll get back with some positive approach. Thank you ❤️
Keep loving ❤️ Keep inspiring 🤩 Keep liking 👍 No sharing 😄