I'm new to SLIM3 and can any body guide me how to connect a mysql database and get output a results from a table.
There are many examples for SLiIM v2 and I want to make in in v3
I'm new to SLIM3 and can any body guide me how to connect a mysql database and get output a results from a table.
There are many examples for SLiIM v2 and I want to make in in v3
You can use the Container to pass around objects to your Routes. Assuming that you are using closures to handle your routes in Slim, than you could do something like this
$app = new \Slim\App();
$container = $app->getContainer();
$container["db"] = new PDO(...); // Replace with your preferred DB Access Method
$app->get("/", function(\Slim\Http\Request $req, \Slim\Http\Response $res, array $args) {
$connection = $this->get("db"); // Continue your request
});
A brief explanation of the above code:
Generic declaration of the usual objects ($app
, $container
, etc). The $container object is (by default) Pimple, a Dependency Injection Container which also implements \ArrayAccess. This allows you to treat the object as an array. Using this ability we can set a value into the Container, which will be stored and allow us to access it later. From there, we create a basic route which will be triggered when requesting /
and use a closure to respond to the request. The closure has been binded to the Container object by slim, allowing us to access the Containers methods from the $this
variable. From there you can treat the object as if you had created it in the function.