Home > Blockchain >  Docker php mysql could not find driver
Docker php mysql could not find driver

Time:10-13

I a trying to configure a PHP MySQL setup in docker containers but I get the following error:

Fatal error: Uncaught PDOException: could not find driver in /var/www/html/chapter5/connection.php:29 Stack trace: #0 {main} thrown in /var/www/html/chapter5/connection.php on line 29

My docker-compose.yml, DockerFile and connection.php scripts are as follows :

version: "3"

services:
  www:
    container_name: playpen_www
    build: .
    restart: 'always'
    ports:
      - '81:80'
    volumes:
      - .:/var/www/html
    depends_on:
      - db
  db:
    container_name: playpen_db
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: pdo-demo
      MYSQL_USER: user
      MYSQL_PASSWORD: password
    ports:
      - '3307:3306'
  adminer:
    image: adminer
    container_name: playpen_adminer
    restart: always
    ports:
      - 8080:8080

FROM php:7.4.24-apache
RUN apt-get update -y && apt-get upgrade -y
RUN apt-get install tree nano -y

// $host = '127.0.0.1';
$host = 'playpen_db';
$port = 3307;
$dbname = 'pdo-demo';
$charset = 'utf8mb4';
$dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset={$charset}";

$options = [ 
    PDO::ATTR_ERRMODE   =>  PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE    =>  PDO::FETCH_ASSOC,
];

try {
    $pdo = new \PDO($dsn, 'user', 'password', $options);
} catch (PDOException $PDOException) {
    print PHP_EOL . "<br><br>" . $PDOException . "<br>";
    throw new PDOException($PDOException->getMessage(), (int) $PDOException->getCode());
}

In the playpen_www container I executed /usr/local/bin/docker-php-ext-enable pdo_mysql and I confirmed both the pdo and pdo_mysql modules are listed as enabled.

CodePudding user response:

Try adding this to your Dockerfile:

RUN docker-php-ext-install pdo_mysql

This will insure that the module is installed in the docker engine whenever you spin up your image.

CodePudding user response:

Quite annoyingly, the problem was with the database name.

In addition to installing pdo_mysql, I changed pdo-demo to pdo_demo in the code and docker-conpose files, rebuilt the containers and the script successfully connected.

  • Related