Adding database query to page or module block

I’m trying to use the code below to create a database connection and run a sql query on either a page (modifying the show.phtml code) or a block from a module, adding to one of the view pages for the module that is .phtml. This code comes from the dev guide-Services and Factories - Omeka S Developer Documentation

$connection = $serviceLocator->get(‘Omeka\Connection’);
$sql = ‘’; // whatever SQL you need to execute
$connection->exec($sql);

however, wherever I add it, it returns “Error
Call to a member function get() on null” for the first line. Where am I going wrong?

The error means $serviceLocator isn’t set.

There’s no out-of-the-box way to get the service locator or the connection service from within a view. The conventional way is to use view helpers, injecting whatever you need via a factory and doing the whatever you need to do there.

thanks! put together a view helper that is working fine.