1

I have a PHP file in the public_html titled categories.php with the following code:

namespace Craft; $craft = require '../craft/app/bootstrap.php'; $categories = $craft->categories->allGroupIds(); 

Running this script results in the following message:

Error error Craft can’t connect to the database with the credentials in craft/config/db.php. 

My craft/config/db.php file looks like this.

return array( '*' => array( 'tablePrefix' => 'craft', ), 'live' => array( 'server' => 'localhost', 'user' => '', 'password' => '', 'database' => '', ), 'staging' => array( 'server' => 'localhost', 'user' => 'DB_USER', 'password' => 'DB_PASSWORD', 'database' => 'DB_NAME', ), 'dev' => array( 'server' => 'localhost', 'user' => 'root', 'password' => 'root', 'database' => 'DB_NAME', ), ); 

I'm not having database trouble anywhere else, only when I try to call any CategoriesService methods. Is there something that I'm failing to understand here?

Solution:

The CRAFT_ENVIRONMENT constant was being set in public_html/index.php, so my craft/config/db.php file could not choose the correct database credentials. The issue was resolved by setting the constant to 'dev' in my categories.php file, like below.

namespace Craft; define('CRAFT_ENVIRONMENT', 'dev'); $craft = require '../craft/app/bootstrap.php'; $categories = $craft->categories->allGroupIds(); 
2
  • The above code works for me in the Happy Lager example site, except the allGroupIds() should be allGroupIds, as this is a property and not a method. That doesn't explain the database error, though. Is your public directory next to your craft directory on the filesystem? Commented May 16, 2016 at 19:35
  • Yes, it sits right next to the craft folder. Commented May 16, 2016 at 22:04

1 Answer 1

0

You don't show how you're defining the 'live', 'staging' and 'dev' keys for the multi-environment config, but most likely you just need to explicitly set the CRAFT_ENVIRONMENT PHP constant in your categories.php file to tell Craft which database credentials to choose.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.