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 trialAnthony Randazzo
13,072 Points"Could not connect to database"
For the life of me, I can't figure out why, but I can't connect to the database. MAMP says that my host is "localhost", my port is "3306" and my username and password are "root". I changed the information in the configure.php file. Nomatter what I do differently, I keep printing "Could not connect to the database." I don't know enough to narrow down what the problem could be. I've spent hours on this. I've changed ports, tried making a new user in myphpAdmin, I've used the mysqli_connect alternative not discussed in this tutorial. Yes, mySQL and Apache servers are on. I'm hoping this is trivial and that someone one here can swoop in and rescue me.
I must note that I didn't put the entire project in the htdocs folder. I'm working on my own project, so I removed the configure.php and database.php files and frankensteined them into my own project. I figured that it wouldn't make a different. I thought I'd still be able to connect to a mySQL db that I made. I just swapped out the name of the db for the shirt project with the one that I made. Please help. Here's the code:
<?php
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME .";port=" . DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Could not connect to the database.";
exit;
}
3 Answers
Carlos Morales
13,880 PointsI didn't take the time to look over all of your code, but it looks like your syntax is wrong. I would avoid using concatenation in your try catch block. Here is an example I found phpro.org that should help you out.
<?php
try {
$dbh = new PDO("mysql:host=**yourhost**;dbname=**yourdbname**", **username**, **password**);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Anthony Randazzo
13,072 PointsThank you, sir. I was able to connect!
Carlos Morales
13,880 PointsAwesome! Glad I could help.