phpmysqldocker-composepdo

Consistent Access Denied error when trying to connect to MySQL DB with PDO


I'm newbie to PHP and I'm trying to get started with it.

I have been following this guide to create a PHP boilerplate for future projects using Docker (I didn't want to use XAMPP cause I like to make my life harder lol).

Everything is working except I'm not able to connect to the MySQL DB. I've tried googling and searching on Stack Overflow but none of the solutions have worked for me. No matter what I try I get the following error every time:

PDOException: SQLSTATE[HY000] [1044] Access denied for user 'admin'@'%' to database 'my_local_db' in /app/public/index.php:14 Stack trace: #0 /app/public/index.php(14): PDO->__construct('mysql:host=db;d...', 'admin', Object(SensitiveParameterValue)) #1 {main}

Exception when trying to connect to DB

Here is my DB service in docker compose:

db:
    image: mysql:latest
    restart: always
    volumes:
      - ./database:/var/lib/mysql    
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: "my_local_db"
      MYSQL_USERNAME: "admin"
      MYSQL_PASSWORD: "admin"
    ports:
      - 3306:3306

Here is my index.php file:

<?php

$host = "db";
$db_name = "my_local_db";
$username = "admin";
$password = "admin";

try {
    $dbh = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
    echo '<h4 style="color: green">Connected to database sucessfully.</h4>';
}
catch (PDOException $e) {
    echo $e;
    echo '<h4 style="color: red">Fail to connect to database.</h4>';
}

I have uploaded the entire project with the bug to my GitHub repo here in case anyone wants to take a look.

Your help would be much appreciated!


Solution

  • Try this,

    1st step: Fix Docker Compose File: Replace MYSQL_USERNAME with MYSQL_USER

    db:
    image: mysql:latest
    restart: always
    volumes:
      - ./database:/var/lib/mysql    
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: "my_local_db"
      MYSQL_USER: "admin"
      MYSQL_PASSWORD: "admin"
    ports:
      - 3306:3306
    

    2nd:

    docker-compose down
    docker-compose up -d --build
    

    3rd: Verify PHP Code: Your index.php code is fine. Ensure the credentials match.

    4th:

        Test MySQL Connection: Use CLI to verify
    docker exec -it <mysql_container_id> mysql -uadmin -padmin my_local_db
    

    In the last just grant permissions if needed:

     GRANT ALL PRIVILEGES ON my_local_db.* TO 'admin'@'%';
    FLUSH PRIVILEGES;