Which is the best way to use database connection in phtml file in Magento 2

Only for fetching single result from the custom table table because most of the time I am facing error like "User mysql_user already has more than 'max_user_connections' active connections" server guy not supporting me they told me to upgrade your server will upgrade the server later.

In ViewModel File 

namespace Satish\Addaction\Catalog;

class SqlConnection{

     * @var \Magento\Framework\App\ResourceConnection
    protected $resourceConnection;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;

     * Get Table name using direct query
    public function getTablename($tableName)
        /* Create Connection */
        $connection  = $this->resourceConnection->getConnection();
        $tableName   = $connection->getTableName($tableName);
        return $tableName;

in phtml file


$viewModel = $block->getViewModel();
$tableName = $viewModel->getTableName('custom_table');
$query = 'SELECT * FROM ' . $tableName;
 * Execute the query and store the results in $results variable
$results = $this->resourceConnection->getConnection()->fetchAll($query);
echo "<pre>";print_r($results);

Your Answer

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

Browse other questions tagged or ask your own question.