Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

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=127.0.0.1;dbname=mydb;port=3306","user","pass");
        var_dump($db);
} catch (Exception $e) {
        echo "Could not connect to the database.";
        exit;
)
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 (http://127.0.0.1/database.php) 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

PDO support => enabled

PDO drivers => mysql, sqlite

pdo_mysql

PDO Driver for MySQL => enabled

Client API version => 5.1.73

Halp.

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 127.0.0.1 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.