Search code examples
phpfat-free-framework

How to use variables in new mysql interface in Fat Free Framework


I'm struggling on this with fat free framework:

$db=new DB\SQL(
    'mysql:host=localhost;port=3306;dbname=mysqldb',
    'admin',
    'p455w0rD'
);

How tu use variables instead on plain text? I'd like to use environment variables and do something like:

$db=new DB\SQL(
    'mysql:host='.getenv('HOST').';port=3306;dbname=mysqldb',
    getenv('USERNAME'),
    getenv('PASSWORD');
);

However, it doesn't work, and I can't find another way to input the sql credentials :( here is the doc: https://fatfreeframework.com/3.7/databases

Here is my error with the code above:

Internal Server Error
SQLSTATE[HY000] [2002] No such file or directory [/Users/kasterby/Documents/yeet/yeet/fatfree-master/lib/DB/SQL.php:519]

Solution

  • No such file or directory Typically means that your MySQL server isn't up and running.

    Specifically to answer your question though, if you want a variable to use instead of hard coding that, that's pretty easy. You can use configuration files or you can create a totally separate file like PHP's ini parse function or even a simple config.php that you would use like so:

    // repo/config.php
    <?php
    return [
        'db_name' => 'database',
        'db_user' => 'someusername',
        // etc
    ];
    
    // repo/public/index.php
    $config = require('config.php');
    $db = new DB\SQL(
        'mysql:host='.$config['db_host'].';port='.$config['db_port'].';dbname='.$config['db_name'],
        $config['db_user'],
        $config['db_pass']
    );
    
    

    Specific to your question though, if you want environment variables, it would depend on if your webserver, but you would have to define environment variables in your webserver config in order to use them. You could also create a .env file similar to how Laravel does it and parse the .env file with this library mentioned here