skip to Main Content

I’m trying to submit a form to a database using PHP and tried to load a .env file containing the database credentials using composer require vlucas/phpdotenv and it gives me an error in my text editor undefined type DotenvDotenvDotenv if i try to load the .env file in the /src file from the Database.php file as seen in the repo. i’m also getting undefined variables error for all the variables as used in during $form_data_db assignment in handleForm.php file. How can I make it all play nicely?

Here is the repository for the project https://github.com/Thebuilderekes/tw-php/tree/try-env

I expect that the credentials in the .env file are recognized form submits successfully to the database.

2

Answers


  1. Chosen as BEST ANSWER

    The solution was that I updated the vlucas/phpdotenv from V2 to V5

    i moved the code below out of the constructor function into the global and put the .env file in the root of my project

     $dotenv = Dotenv::createImmutable(__DIR__);
     $dotenv->load();
    

    and used $_ENV instead.

    
        $hostname = $_ENV['HOSTNAME'];
        $dbname = $_ENV['DBNAME'];
        $username= $_ENV['USERNAME'];
        $password = $_ENV['PASSWORD'];
    
    

    This is a new branch of the working code https://github.com/Thebuilderekes/tw-php/blob/try-env-with-gitignore

    Thank you for the support


  2. Maybe, you can try to load database connection parameters directly from the environment variables inside the Database class constructor without passing them as parameters. Or try to get environment variables in handleform.php then pass them to database class. I mean:

    use DotenvDotenv;
    
    class Database {
        protected $connection;
    
        public function __construct() {
            // Load environment variables
            $dotenv = DotenvDotenv::createImmutable(__DIR__ . "/src");
            $dotenv->load();
            
            // Get database connection parameters from environment variables
            $hostname = getenv('HOSTNAME');
            $dbname = getenv('DBNAME');
            $username = getenv('USERNAME');
            $password = getenv('PASSWORD');
            
            // Your following codes..
        }
    }
    

    or in your handleform.php:

    $hostname = getenv('HOSTNAME');
    $dbname = getenv('DBNAME');
    $username = getenv('USERNAME');
    $password = getenv('PASSWORD');
    
    $form_data_db = new Database($hostname, $dbname, $username, $password);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search