Database configuration
Create the file src/settings.php inside your api folder and place the following code
"db" => [
"host" => "locahost",
"dbname" => "your-database-name",
"user" => "your-mysql-user",
"pass" => "your-mysql-password"
],
Create the file src/dependencies.php inside your api folder and place the following code
$container['db'] = function ($c) {
$settings = $c->get('settings')['db']; // From src/settings.php
$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;
};
This is injecting the database object into container, and you can now access all users
** For creating the users table see Create users table post
require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App;
$app->get('/', function ($request, $response) {
return 'hello world';
});
$app->post('/postit', function ($request, $response) {
$input = $request->getParsedBody();
return $this->response->withJson($input);
});
$app->get('/all', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
$users = $sth->fetchAll();
return $this->response->withJson($users);
});
$app->run();