PHP cant connect to MySQL

2019-03-03 08:21发布

$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();
    }

5条回答
放荡不羁爱自由
2楼-- · 2019-03-03 08:57

Your $password variable is empty ((using password: NO)) then you trying log into www-data user without password, and server result is access denied. Propably this user have setted password.

查看更多
Root(大扎)
3楼-- · 2019-03-03 08:59

I think the problem is that, you are trying to connect to the database twice. Somewhere in your code, you are already trying to connect to the database with username as "www-data"...... and again you are connecting to the database with username "root".

Also the password you are providing with the username "www-data" is wrong, thats y you getting the error message.

查看更多
▲ chillily
4楼-- · 2019-03-03 09:00
$username="root";
$password="root";
$database="test";

    function Save($name)
    {
        global $username;
        global $password;
        global $database;

        $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();
    }
查看更多
唯我独甜
5楼-- · 2019-03-03 09:02

Did you give $username and $password values? Something like this?

$username="root";
$password="";
查看更多
The star\"
6楼-- · 2019-03-03 09:18

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.

查看更多
登录 后发表回答