You can't put PHP code into Twig, and there's no straightforward way to write custom DB queries in Twig. That's by design – Twig is a templating language, not meant for custom queries or processing.
Instead, you should provide a service object with utitily methods that you can call from Twig. Depending on your use-case, you can accept parameters (for example, arguments to a query) to get the flexibility you need.
First, look at the link above to learn more about services. If you're building a plugin, your service class goes in there. If you're working on some site-specific functionality, you can put it in a module instead. Once you have defined your service class and added it as a component to your plugin or module, you need to make it available to Twig – see the documentation on Extending Twig. For a plugin, extending the CraftVariable
would be the most common way to provide a custom service object to Twig. In a module, I'd use a Twig extension instead, though that's mostly preference.