Defining MySQL connection in Slim Framework?
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/
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
});
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;
}