可以使用终端访问mysql数据库,但我得到"访问被拒绝"使用php时的消息

时间:2014-12-29 08:24:00

标签: php mysql linux ubuntu

在我的终端登录mysql时,一切正常。但是当我用

运行我的网页时
$conn = new mysqli("localhost", "root", "password");
if($conn->connect_error) {
   die("connection failed: " . $conn->connect_error);
}
echo "connected successfully";

我得到“连接失败:访问被拒绝用户'root'@'localhost'(使用密码:YES)”。 我试过重置root密码。我尝试过授予root权限。我绝对肯定我在php文件中正确输入了用户名和密码。

我在Ubuntu 14.04计算机上运行LAMP服务器。我有php 5.5.9,mysql 5.5.40和apache 2.4.7。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

PHP要求您填写您尝试连接的数据库的用户名,密码和数据库名称:http://php.net/manual/en/function.mysql-connect.php

$conn = new mysqli("localhost", "root", "password", "database");

答案 1 :(得分:0)

尝试mysqli_connect_errno()

$conn = new mysqli("localhost", "root", "password");
if(mysqli_connect_error()) {
   die("connection failed: " . mysqli_connect_error());
}
echo "connected successfully";

结账手册:

connect_error

Warning The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.