Use either PDO or Doctrine DBAL for database connections.
You might be trying to access a variable in a function that is outside that function, but in PHP you can't just do that. The scope is a bit fucked up. Cant say more without seeing the code itself.
Also, access the API with JavaScript using AJAX. (preferred)