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

Databases

Why can't I connect to my localhost database?

I have a created a test database to work with, called "music_online", and I'm trying to pull data from it using PHP. However, for some reason, I can't connect to the database.

I don't know if its my code, or my setup to the database. This is the first time I've tried working with a database.

The error that I continue to receive is "Database connection failed: Access denied for user 'music_online'@'localhost' (using password: NO) (1045)"

Here is my code:

<?php
// Create a database connection
$dbhost = "localhost";
$dbname = "music_online";

$connection = mysqli_connect($dbhost, $dbname);

//Test if connection occurred
if(mysqli_connect_errno()) {
    die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")");
}
?>
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="main.css">
    </head>
    <body>
        <h1>Music Info</h1>
        <form method="POST" id="searchForm">
            <input type="text" id="searchBox" name="search" placeholder="search...">
            <input type="submit" name="submit" value="search">
        </form>
    </body>
</html>
<?php
    // Close database connection
    mysqli_close($connection);
?>

please help

Thank you

1 Answer

Corey Johnson
PLUS
Corey Johnson
Courses Plus Student 10,192 Points

When you created the DB "music_online," did you also create a user? If so, you need to pass that info in your mysql connect statement. Or you can use the root credentials. Using root is not advisable but for local dev it is not as much of a "no-no." (but i would still try and create a separate user and grant them access to this DB). Once you have the user create, your code would look something like this:

<?php
// Create a database connection
$dbhost = "localhost";
$dbname = "music_online";
$dbuser = "username";
$dbpassword = "thepassword";

$connection = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);

Change the "username" and "password" to the appropriate values.

Hope this helps.

Hey, Corey, thank you for getting back to me, man. Your advice worked