PHP无法连接MySQL
$link = mysql_connect('localhost', $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
我收到此错误:
无法连接:用户“www-data”@“localhost”访问被拒绝(使用密码:否)
为什么?
编辑:
$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();
}
$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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您是否指定了
$username
和$password
值?像这样的东西吗?Did you give
$username
and$password
values? Something like this?您的
$password
变量为空((使用密码:NO)
),然后您尝试在没有密码的情况下登录www-data
用户,并且服务器结果访问被拒绝。可能该用户已经设置了密码。Your
$password
variable is empty ((using password: NO)
) then you trying log intowww-data
user without password, and server result is access denied. Propably this user have setted password.从您的编辑来看,问题似乎是范围界定问题。
您尝试在函数内部建立连接,其中
$username
、$password
和$database
变量是在该函数外部定义的。我建议您阅读手册的变量作用域部分,并打开您的正如 @netcoder 在问题评论中建议的那样报告错误。
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.
我认为问题在于,您尝试连接到数据库两次。
在代码中的某个位置,您已经尝试使用用户名“www-data”连接到数据库......并且您再次使用用户名“root”连接到数据库。
此外,您使用用户名“www-data”提供的密码是错误的,这就是您收到错误消息的原因。
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.