Search code examples
phpmysqlmysql-error-1045

PHP cant connect to MySQL


$link = mysql_connect('localhost', $username, $password);
if (!$link) 
{
     die('Could not connect: ' . mysql_error());
}

I get this error:

Could not connect: Access denied for user 'www-data'@'localhost' (using password: NO)

Why?

Edit:

$username="root";
$password="root";
$database="test";

    function Save($name)
    {
        $link = mysql_connect('localhost', $username, $password);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        @mysql_select_db($database) or die( "Unable to select database");
        $query = "INSERT INTO test (name)" .
                 "VALUES ('" . $name . "')";
        mysql_query($query);
        mysql_close();
    }

Solution

  • From your edit, the issue appears to be a scoping one.

    You're attempting to make a connection inside a function where the $username, $password and $database variables are defined outside that function.

    I suggest you read the Variable Scope section of the manual and turn up your error reporting as @netcoder suggests in the question comments.