Skip to content
Advertisement

PDO Connection with Json data [closed]

I want to get a PDO Connection with data from a json config file.

I currently have this, but it doesn’t work and throws a fatal PDOException error

$cfg = json_decode("../config/config.json");
$host = $cfg["mysql"]["host"];
$port = $cfg["mysql"]["port"];
$database = $cfg["mysql"]["database"];
$username = $cfg["mysql"]["username"];
$password = $cfg["mysql"]["password"];

try {
   $mysql = new PDO("mysql:dbname=$database;host=$host:$port", $username, $password);
} catch (PDOException $e) {
   echo "Error while connecting to MySQl Database: " . $e->getMessage();
}

And here the config.json

{
  "mysql": {
    "host": "locahost",
    "port": 3306,
    "database": "test",
    "username": "root",
    "password": ""
  }
}

Advertisement

Answer

You need to read config file contents first and then decode it as an array because you used array syntax [] otherwise you’ve to use access -> syntax that is for objects.

$cfg = json_decode(file_get_contents("../config/config.json"),true);

assoc

When TRUE, returned `objects` will be converted into associative `arrays`

depth

DEMO: https://3v4l.org/qN35T

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement