Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Php PDO can connect to a mysql database on command line but not on my apache webserver. Why?

I am running this script:

<? php

try {
        $db = new PDO("mysql:host=;dbname=mydb;port=3306","user","pass");
} catch (Exception $e) {
        echo "Could not connect to the database.";
echo "Awww Yeeaa";

When I run in command line I am able to connect. I get the output:

$ php database.php

object(PDO)#1 (0) {}

Awww Yeeaa

BUT in the browser ( when I access the file I get:

Could not connect to the database.

Why is this happening? I have run phpinfo; and it tells me this about PDO:


PDO support => enabled

PDO drivers => mysql, sqlite


PDO Driver for MySQL => enabled

Client API version => 5.1.73


2 Answers

Found the answer here: http://stackoverflow.com/questions/8139451/pdo-connection-works-from-command-line-but-not-through-apache

I should have mentioned I'm on a CentOS box. Apparently on Red Hat derived linux distros the default policy is to prevent webservers from making connections to databases or other servers.

As root you must run:

setsebool -P httpd_can_network_connect=1

setsebool -P httpd_can_network_connect_db=1

instead of can you try localhost instead?? I know it means the same thing but worth a try. Cant see anything wrong with your code.

Tried it out. Unfortunately no difference.