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! While you're at it, check out some resources Treehouse students have shared here.

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

Parvez Noor
PLUS
Parvez Noor
Courses Plus Student 15,917 Points

Can't connect to SQL database. For some reason, it works fine on one of my websites, but fails on another. Any clue?

Hi guys,

I use the following code, in connection.php which i include at the top of pages which I need to access a SQL database I've created.

I use this exact same code on another website which works completely fine. (See the console.log of this website to see the connection to the database: https://phlegethontic-flash.000webhostapp.com/art.php?cat=pottery

However, on a current project I am working on, the connection always fails. The error code is says is: SQLSTATE[HY000] [2002] No such file or directory. (See the console.log of this website to see how, even though the code for connection to the database is the same, on this website it doesn't connect.): http://www.mpowerelectrics.co.uk/areas.php

What is happening? Can anyone shed any light?

<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$database = "mydatabase";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      echo '<script>console.log("Connected successfully")</script>'; 
    } catch(PDOException $e) {    
    echo '<script>console.log("Connection failed: "' . $e->getMessage() . ')</script>'; 
    }

1 Answer