Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


How do I show data from my database in SLIM/TWIG templates?

Hello everyone,

As I watched the videos of Slim/Twig I decided to go this route for my website. It works fine now but one problem. I have absolutely no idea on how to integrate mysql database.

Here is my index.php file where is my slim and my connection to the database.


use \Psr\Http\Message\ServerRequestInterface as Request;

use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';

$app = new \Slim\App();

$container = $app->getContainer();

$container['view'] = function ($container) {

$view = new \Slim\Views\Twig('templates', [

    'cache' => false
$view->addExtension(new \Slim\Views\TwigExtension(

return $view;


// Render Twig template in route $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'home.twig' ); });

$app->get('/about', function ($request, $response, $args) { return $this->view->render($response, 'about.twig' ); });

$app->get('/contact', function ($request, $response, $args) { return $this->view->render($response, 'contact.twig' ); });

$app->get('/upload', function ($request, $response, $args) { return $this->view->render($response, 'upload.twig' ); });

$dsn = 'mysql:host=localhost;dbname=database;charset=utf8'; $usr = 'root'; $pwd = 'root';

$pdo = new \Slim\PDO\Database($dsn, $usr, $pwd);

try { $selectStatement = $pdo->query('SELECT * FROM hotels ORDER BY REPLACE(name, "The ", "")'); } catch(Exception $e) { echo $e->getMessage(); die(); };

$data = $selectStatement->fetchAll(PDO::FETCH_ASSOC);

$app->run(); ?>


And here is a part in my home.twig file which contains a dropdown menu with the $data items that I want to display.

''' <div id="dropdownmob"> <select class="select" onchange="location = this.options[this.selectedIndex].value;"> <option>Select an item</option> <optgroup label="A-Z"> <?php foreach($data as $items){ echo '<option value="items.php?id='.$items["id"].'">' .$items["name"].'</option>'; } ?> </select> </div> '''

Obviously, it doesn't work right now because before, my home.twig file was my initial index.php file without slim/twig.

Help me, I'm lost :(

1 Answer