Home > OS >  PHP Docker app throwing error when submitting data to the database
PHP Docker app throwing error when submitting data to the database

Time:06-12

I am new to docker and I am trying to dockerise a simple php registration app. When the credentials are hardcoded into the database connection file the application works as it should. However i introduced a .env file into the mix to store the credentials and since then i am getting an error whenever i click submit. Below are my code snippets:

Docker Compose

version: '3'

services:
  web:
    build: ./frontend
    ports:
      - "8000:80"
    stdin_open: true
    tty: true
    env_file:
      - ./env/mysql.env

  db:
    image: mysql:latest
    container_name: webappdb
    restart: always
    volumes:
      - /home/fikradev/dbvolume:/home/app
    env_file:
      - ./env/mysql.env

  monitor:
    image: phpmyadmin
    restart: always
    ports:
      - 8080:80
    environment:
      - PMA_ARBITRARY=1

volumes:
  db:

.env file contents

MYSQL_ROOT_PASSWORD=@dbuser
MYSQL_DATABASE=issuetrackdb
MYSQL_USER=dbuser
MYSQL_PASSWORD=password

dbconnect php file

<?php
$conn = mysqli_connect('webappdb', '${MYSQL_USER}', '${MYSQL_PASSWORD}', '${MYSQL_DATABASE}');

if($conn == false){
    die("ERROR - Could not connect: " . mysqli_connect_error());
}
?>

This is the error i am getting

Warning: mysqli_connect(): (HY000/1045): Access denied for user '${MYSQL_USER}'@'172.31.0.3' (using password: YES) in /var/www/html/dbconnect.php on line 2
ERROR - Could not connect: Access denied for user '${MYSQL_USER}'@'172.31.0.3' (using password: YES)

I have been on this for hours. Grateful if someone could point out where i am going wrong.

CodePudding user response:

By setting a .env file in docker-compose.yml, you are providing variables to the environment your PHP application is running in. These are not automatically made available as variables in your PHP script. You can use getenv() to retrieve them:

$conn = mysqli_connect('webappdb', getenv('MYSQL_USER'), getenv('MYSQL_PASSWORD'), getenv('MYSQL_DATABASE'));

CodePudding user response:

Try to replace this:

<?php
$conn = mysqli_connect('webappdb', '${MYSQL_USER}', '${MYSQL_PASSWORD}', '${MYSQL_DATABASE}');

if($conn == false){
    die("ERROR - Could not connect: " . mysqli_connect_error());
}
?>

with this:

<?php
$conn = mysqli_connect('webappdb', MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);

if($conn == false){
    die("ERROR - Could not connect: " . mysqli_connect_error());
}
?>
  • Related