1

I am new to Magento 2, it is normal to use the usual way

$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

or is there anyway around to get informationfrom the database

  • You will get database detils from app/etc/env.php file. – kunj Jun 14 '18 at 8:28
2

To connect to the database from within a PHP script, you don't need to use the mysqli_* functions. Magento 2 is designed so the database you use (MySQL, PostGreSQL, etc) should be totally transparent to it.

In fact, you don't even need to define your own database connection, unless your module is doing something which might require it's own connection, e.g. Doing a heavy amount of reads/writes.

If you're building a module which needs to write/read information from the database, you should look at the Service Contract design pattern. It abstracts away a lot of this low-level (i.e. Configuring a connection) stuff and allows you to focus on building the logic of your module. Service Contracts are described in greater detail in the Dev Docs: https://devdocs.magento.com/guides/v2.2/extension-dev-guide/service-contracts/service-contracts.html

If you just need to pull out some data from existing modules, then look into creating a Test Rig script, which bootstraps the Magento backend (but not the frontend) and allows you to read from the database in the same way Magento 2 does, but without having to write a full module. See this question for more details: How can I bootstrap Magento 2 in a test.php script?

Finally, directly connecting to the database and executing queries like Prashant Patel's answer is also bad practice, because Magento 2 uses things like events and plugins in the code and foreign keys and triggers in the database in order to ensure (and preserve) data integrity.

Directly querying the database using SQL statements like this bypasses these checks and balances and could leave stale or invalid data in your database, amongst other problems.

Edit:

Here is a simple 'bootstrap' app which will query the database for all products with a specific SKU:

Create file test.php in the root folder of Magento (the folder which contains CHANGELOG.md, CONTRIBUTING.md, etc):

<?php
/**
 * Application entry point
 *
 * Example - run a particular store or website:
 * --------------------------------------------
 * require __DIR__ . '/app/bootstrap.php';
 * $params = $_SERVER;
 * $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'website2';
 * $params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website';
 * $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
 * \/** @var \Magento\Framework\App\Http $app *\/
 * $app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
 * $bootstrap->run($app);
 * --------------------------------------------
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @link https://magento.stackexchange.com/questions/39981/how-can-i-bootstrap-magento-2-in-a-test-php-script
 */
try {
    require __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo <<<HTML
<div style="font:12px/1.35em arial, helvetica, sans-serif;">
    <div style="margin:0 0 25px 0; border-bottom:1px solid #ccc;">
        <h3 style="margin:0;font-size:1.7em;font-weight:normal;text-transform:none;text-align:left;color:#2f2f2f;">
        Autoload error</h3>
    </div>
    <p>{$e->getMessage()}</p>
</div>
HTML;
    exit(1);
}

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('TestApp');
$bootstrap->run($app);

Now create another new PHP file in the same folder called TestApp.php:

<?php

/**
 * Class TestApp
 *
 * Run me from the command file: php -f test.php
 * Run me from a browser: Visit http://yourwebsite.example/test.php
 *
 * @link https://magento.stackexchange.com/questions/39981/how-can-i-bootstrap-magento-2-in-a-test-php-script
 */
class TestApp extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface
{

    /**
     * @return \Magento\Framework\App\Response\Http
     */
    public function launch()
    {
        // Prevents 'Area code not set' error
        parent::launch();

        /** @var \Magento\Framework\App\ObjectManager $objectManager */
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        /** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder */
        $searchCriteriaBuilder = $objectManager->create(\Magento\Framework\Api\SearchCriteriaBuilder::class);

        /** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
        $productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);

        $searchCriteria = $searchCriteriaBuilder
            ->addFilter(
                \Magento\Catalog\Api\Data\ProductInterface::SKU,
                'ABSED5045B' // The name of the product
            )
            ->create();

        $products = $productRepository->getList($searchCriteria)->getItems();

        foreach ($products as $product) {
            echo ("{$product->getSku()}: {$product->getId()}") . PHP_EOL;
        }

        // The method must end with this line
        return $this->_response;
    }

    /**
     * @param \Magento\Framework\App\Bootstrap $bootstrap
     * @param \Exception                       $exception
     *
     * @return bool
     */
    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
    {
        return false;
    }
}
  • Really good explanation but still cant figure out how to get the data, i want to do a look up for a given input in the website, can you send me any code that does this? – Compu Scie Jun 14 '18 at 8:40
  • @CompuScie Updated my answer with a simple bootstrap app which explains how to do just that – ProcessEight Jul 30 '18 at 14:06
1

Try this Code:

use \Magento\Framework\App\ResourceConnection\ConnectionFactory;

class Dbconfig extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        ConnectionFactory $connectionFactory
    ) {
        $this->connectionFactory = $connectionFactory;
        parent::__construct($context);
    }

    public function getConnection()
    {
        $db = $this->connectionFactory->create(array(
            'host' => 'localhost',
            'dbname' => 'databasename',
            'username' => 'username',
            'password' => 'password',
            'active' => '1',
        ));
        return $db;
    }

    public function getInformationfrom()
    {
        $db = $this->getConnection();
        $tableName = "Your Table name";
        $readresult = $db->prepare("SELECT * from $tableName");
        echo "<pre>";
        print_r($readresult->fetch());
        exit;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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