Thursday, October 14, 2021

Set MySQL connection Slim framework 4

  • config 2 file app/settings.php and app/dependencies.php

app/settings.php

 "db" => [
                    'driver' => 'mysql',
                    'host' => 'localhost',
                    'username' => 'root',
                    'database' => 'slim_test',
                    'password' => '',
                    'charset' => 'utf8mb4',
                    'collation' => 'utf8mb4_unicode_ci',
                    'flags' => [
                        // Turn off persistent connections
                        PDO::ATTR_PERSISTENT => false,
                        // Enable exceptions
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        // Emulate prepared statements
                        PDO::ATTR_EMULATE_PREPARES => true,
                        // Set default fetch mode to array
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                    ],
                ],


 app/dependencies.php

PDO::class => function (ContainerInterface $c) {
 
            $settings = $c->get(SettingsInterface::class);
 
            $dbSettings = $settings->get('db');
 
            $host = $dbSettings['host'];
            $dbname = $dbSettings['database'];
            $username = $dbSettings['username'];
            $password = $dbSettings['password'];
            $charset = $dbSettings['charset'];
            $flags = $dbSettings['flags'];
            $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
            return new PDO($dsn, $username, $password);
        },

ทดสอบใน app/routes.php

 $app->get('/db-test', function (Request $request, Response $response) {
        $db = $this->get(PDO::class);
        $sth = $db->prepare("SELECT * FROM user ORDER BY id desc limit 100");
        $sth->execute();
        $data = $sth->fetchAll(PDO::FETCH_ASSOC);
        $payload = json_encode($data);
        $response->getBody()->write($payload);
        return $response->withHeader('Content-Type', 'application/json');
    });    
};

Ref

  • https://arjunphp.com/how-to-connect-to-mysql-database-in-slim-framework-4/
  • https://odan.github.io/2020/04/05/slim4-multiple-pdo-database-connections.html

No comments:

Post a Comment

Popular Posts