Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining MySQL connection in Slim Framework?

Tags:

php

slim

I am hearing great things about Slim Framework- and it seems easy. Except none of the tutorials address where to put the MySQL info.

I see things like $dbCon = getConnection();

But where do I define the username/pw/db/host etc?

like image 601
itamar Avatar asked Jul 14 '14 19:07

itamar


3 Answers

First thing first lets open src/settings.php file and configure database connection details to the settings array as shown below.

<?php
return [
  'settings' => [
      'displayErrorDetails' => true, // set to false in production

      // Renderer settings
      ....
      ....    

      // Monolog settings
      ....
      ....

      // Database connection settings
      "db" => [
          "host" => "localhost",
          "dbname" => "slim3",
          "user" => "root",
          "pass" => "xxxxx"
      ],
   ],
];

There are many database libraries available for PHP, but this example uses PDO. Now open your src/dependencies.php file and configure database library as shown below. you can use your own libraries by adapting the example.

// DIC configuration
$container = $app->getContainer();

...
...
...

// PDO database library
$container['db'] = function ($c) {
    $settings = $c->get('settings')['db'];
    $pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
        $settings['user'], $settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

via: https://arjunphp.com/configure-load-database-slim-framework-3/

like image 160
Ivan Fretes Avatar answered Sep 26 '22 06:09

Ivan Fretes


Its best to keep these credentials in a local configuration file. I add a configs folder outside the web root and add a local.php configuration file to that.

....
/configs
    local.php
/public
/vendor
....

You can configure anything you like, but here's the DB:

<?php
// configs/local.php
return array(
    'db' => ['user' => 'root', 'password' => 'root']
);

Then include the file in your app and create the connection:

// public/index.php
$config = include(__DIR__ . '/../configs/local.php');
$db = new PDO("mysql:host=localhost;dbname=dbname", $config['db']['user'], $config['db']['password'] );

$app->get('/', function () use ($app, $db) {
    // do something with your db connection
});
like image 34
ForrestLyman Avatar answered Sep 22 '22 06:09

ForrestLyman


You can define a function in your file (e.g. index.php)

    function getConnection() {
    $dbhost="yourdbhost";
    $dbuser="yourdbuser";
    $dbpass="yourdbpass";
    $dbname="yourdb";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
    }
like image 40
mjpramos Avatar answered Sep 26 '22 06:09

mjpramos