1

I want to update data to particular value in database. How to write script for the below query

    update tablename set name="Test" where id="4"

2 Answers 2

2

Create a file e.g root_magento_dir/pub/example_file.php. Paste this code in your file.

<?php
include(__DIR__ . '/../app/bootstrap.php');

use Magento\Framework\App\Bootstrap;


$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_CRONTAB);

$resourceConnection = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resourceConnection->getConnection();
$connection->query('update tablename set name="Test" where id="4"');

die("Done");

Run this file via URL https://www.example.com/example_file.php Or you can run it directly via Shell cd path/to/pub/directory && php example_file.php.

Thank you.

4
  • You can remove that die if you want, It's just a script therefore it doesn't matter if we kill it at the end. I've used that die just to indicate that script has done it's work Dec 1, 2021 at 12:23
  • But don't forget to delete this script after your work is done because this could be accessed via URL and it makes our site vulnerable for hackers. Dec 1, 2021 at 12:24
  • yes so that i need this script through upgradeData
    – User0434
    Dec 1, 2021 at 12:29
  • can u plz provide solution with upgradedata.php
    – User0434
    Dec 1, 2021 at 13:03
2

Update increment version in module.xml like setup_version="1.0.1", make sure in db setup_module table data should be 1.0.0 and add below code in upgradeData.php

<?php

namespace Namespace\Module\Setup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;


class UpgradeData implements UpgradeDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        if (version_compare($context->getVersion(), "1.0.1", "<")) {
              $table = $setup->getTable('test');
              $setup->getConnection()->update($table, ['name' => 'test123'], 'id IN (1)');
        }

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.