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 trialParvez Noor
Courses Plus Student 15,917 PointsCan'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. However, on a current project I am working on, the connection always fails.
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>';
}
2 Answers
Jonathan Grieve
Treehouse Moderator 91,253 PointsCould there be a problem with the SQL for the database that's failing? What error message is your website returning? Perhaps there's a clue in there that can help you work out the bug.
Parvez Noor
Courses Plus Student 15,917 PointsThe thing is, I have the EXACT same code on this site:
https://phlegethontic-flash.000webhostapp.com/art.php?cat=pottery
and this site:
http://www.mpowerelectrics.co.uk/areas.php
But as you can see in the console, on one, it says connection successful, and the other, connection failed.
It's really baffling me :S.
The error message for when it fails says:
SQLSTATE[HY000] [2002] No such file or directory