How to connect Postgresql database in Slim framework with PDO?

I work with MYSQL database in slim framework. Its perfectly worked. But going to connect Postgresql, It not connected as well.

Here is the sample Coding: (settings.php)

```
declare(strict_types=1);
    use App\Application\Settings\Settings;
    use App\Application\Settings\SettingsInterface;
    use DI\ContainerBuilder;
    use Monolog\Logger;
    
    return function (ContainerBuilder $containerBuilder) {
    
        $containerBuilder->addDefinitions([
            SettingsInterface::class => function () {
                return new Settings([
                    'displayErrorDetails' => true, // Should be set to false in production
                    'logError'            => true,
                    'logErrorDetails'     => true,
                    'logger' => [
                        'name' => 'slim-app',
                        'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
                        'level' => Logger::DEBUG,
                    ],
                        "db" =>
                               [
                                'driver'   => 'pgsql',
                                'host'     => 'localhost',
                                'port'     => '5433',
                                'database' => 'test_db',
                                'username' => 'postgres',
                                'password' => 'password',
                                'prefix'   => '',
                                'schema'   => 'public',
                            ]
    
                    ]);
            }
        ]);
};
```

Here is the code : (dependencies.php)

```
    <?php
    declare(strict_types=1);

    use App\Application\Settings\SettingsInterface;
    use DI\ContainerBuilder;
    use Monolog\Handler\StreamHandler;
    use Monolog\Logger;
    use Monolog\Processor\UidProcessor;
    use Psr\Container\ContainerInterface;
    use Psr\Log\LoggerInterface;

    return function (ContainerBuilder $containerBuilder) {
        $containerBuilder->addDefinitions([
            LoggerInterface::class => function (ContainerInterface $c) {
                $settings = $c->get(SettingsInterface::class);

                $loggerSettings = $settings->get('logger');
                $logger = new Logger($loggerSettings['name']);

                $processor = new UidProcessor();
                $logger->pushProcessor($processor);

                $handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
                $logger->pushHandler($handler);

                return $logger;
            },
             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'];
                $port = $dbSettings['port'];
                $dsn = new PDO ("pgsql:host=$host;port=$port;dbname=$dbname");
               return new PDO($dsn, $username, $password);

            },

        ]);
    };
```

Here checking for database connection : (routes.php)

    ```
    <?php
    declare(strict_types=1);

    use App\Application\Actions\User\ListUsersAction;
    use App\Application\Actions\User\ViewUserAction;
    use Psr\Http\Message\ResponseInterface as Response;
    use Psr\Http\Message\ServerRequestInterface as Request;
    use Slim\App;
    use Slim\Interfaces\RouteCollectorProxyInterface as Group;

    return function (App $app) {
        $app->options('/{routes:.*}', function (Request $request, Response $response) {
            // CORS Pre-Flight OPTIONS Request Handler
            return $response;
        });

        $app->get('/', function (Request $request, Response $response) {
            $response->getBody()->write('Hello world!');
            return $response;
        });

        $app->group('/users', function (Group $group)
        {
            $group->get('', ListUsersAction::class);
            $group->get('/{id}', ViewUserAction::class);
        });

        $app->post('/db-select', function (Request $request, Response $response)
        {
            $db = $this->get(PDO::class);
            $sth = $db->prepare("SELECT * FROM login");
            $sth->execute();

            $data = $sth->fetchAll(PDO::FETCH_ASSOC);
            $payload = json_encode($data);
            $response->getBody()->write($payload);
            return $response->withHeader('Content-Type', 'application/json');
        });

    };
    ```

If I run the command such as localhost:8000/db-select Its give me the following error:

```
{
    "statusCode": 500,
    "error": {
        "type": "SERVER_ERROR",
        "description": "SQLSTATE[08006] [7] fe_sendauth: no password supplied"
    }
}
```

I worked the sample code for MYSQL it worked perfect. What else missed for Postgresql connection?

Regards

fe_sendauth: no password supplied"

Here is a bug:

$dsn = new PDO ("pgsql:host=$host;port=$port;dbname=$dbname");

return new PDO($dsn, $username, $password);

Try this:

return new PDO("pgsql:host=$host;port=$port;dbname=$dbname", $username, $password);
1 Like

Wow. Thanks sir. Its works perfectly.

1 Like