0

Hello so I am using slim framework and decided to use PDO and here is my current code:

$app->get('/', function () use ($app) {
    try {
        $dbh = new PDO('mysql:host=localhost;dbname=tcgovernment_website', 'root', '');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
    }
    $app->render('index.html');
});

$app->get('/template', function () use ($app) {
    try {
        $dbh = new PDO('mysql:host=localhost;dbname=tcgovernment_website', 'root', '');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
    }
    $app->render('template.html');
});

as you can see from the code, I keep repeating the connection in every $app. Is there a way to only call a single line in every $app so I won't have to keep repeating the database connection code? Thank you.

wobsoriano
  • 12,348
  • 24
  • 92
  • 162

1 Answers1

0

I'm not sure about Slim Framework, but you can pass along multiple variables (declared outside the scope) into your use.

$app->get('/', function () use ($app, $dbh) { }
vonUbisch
  • 1,384
  • 17
  • 32