Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By stratcr on
I am very new to module development, I have a "hosted" drupal 8 site that I am allowed to give them modules to install and they verified that the proper php components were installed for sqlsvr (sql server communication). I have an external SQL Server that I would like to display data within a module. I am including the database connection in the module because they will not let me change the settings.php for the site.
How do I display the data from the database on a page/block/whatever in the site and is this code even correct?
Files so far:
TestModule.info.yml
TestModule.module
<?php
/**
* @file
* Drupal site-specific configuration file.
*/
$databases['db']['default'] = array (
'database' => 'DATABASENAME',
'username' => 'SQLSERVERUSERNAME',
'password' => 'SQLSERVERPWD',
'host' => 'ServerNameIP',
'port' => '1433',
'driver' => 'sqlsvr',
'prefix' => '',
);
Database::addConnectionInfo('db', 'default',$databases);
db_set_active('db');
//Connection to the database
$con = \Drupal\Core\Database\Database::getConnection('default','db');
//Execute Queries Here
$query = $con->select('Staff', 't')
->fields('t', ['Session']);
$query->condition('Session', "%" . $query->escapeLike("17") . "%", 'LIKE');
$result = $query->execute()->fetchAll();
db_set_active(); //without the parameter means set back to the default for the site
drupal_set_message(tan('The queries have been made.'));