2

I was looking for a solution for a config/details file. I found this solution interesting, but instead of hardcode the values, I would like to retrieve them from a database.

I'm new to PDO as well, but my solution, for now, is as follow (config.php):

try {
    $db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'user', 'pwd');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $db->query("SELECT name, value FROM config");
    $configs = $stmt->fetchAll();

    return [
        array_column($configs, 'value', 'name')
    ];

} catch(PDOException $e) {
    echo "Error: ".$e->getMessage();
}

Then I get a response like this:

Array ( [0] => Array ( [SITENAME] => Pionérhytta [MAXGUESTS] => 5 ) )

And I would need to write like this to get value out (index.php):

<?php $config = include('../config/config.php'); ?>
...
<?=$config[0]['SITENAME']?>

This works, but I would like to remove the [0] and write $config['SITENAME'] to get the value.

Is there any solution for this?

In advance, thanks for the help

ERR0
  • 57
  • 6

2 Answers2

4

Your array_column() returns an associative array. It is not necessary to wrap it in another array:

return array_column($configs, 'value', 'name');
Syscall
  • 19,327
  • 10
  • 37
  • 52
1

Just another solution, using fetchAll() to do the work, using a combination of PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC allows you to fetch the result of the SQL statement with the first column as the key and the rest of the values as the value ...

    $stmt = $db->query("SELECT name, value FROM config");
    $configs = $stmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);

    return $configs;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55