【问题标题】:How to connect Postgresql database in Slim framework with PDO?如何将 Slim 框架中的 Postgresql 数据库与 PDO 连接?
【发布时间】:2021-05-06 17:59:27
【问题描述】:

我在苗条的框架中使用 MYSQL 数据库。它完美地工作。 但是要连接Postgresql,它也连接不上。

这里是示例编码:(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',
                            ]
    
                    ]);
            }
        ]);
};

这里是代码:(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);

        },

    ]);
};

这里检查数据库连接:(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');
    });

};

如果我运行localhost:8000/db-select之类的命令,它会给我以下错误:

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

我为 MYSQL 编写了示例代码,它运行良好。 Postgresql 连接还有什么遗漏?

【问题讨论】:

    标签: php postgresql slim


    【解决方案1】:

    检查 PostgreSQL 扩展是否已启用

    extension=pdo_pgsql

    你也可以从这个问题中得到帮助

    fe_sendauth: no password supplied error in postgresql + laravel

    【讨论】:

      【解决方案2】:

      这是一个错误:

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

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多