PHP MySQL连接错误

时间:2017-02-02 12:42:59

标签: php mysql

我有一个问题,真的困扰我对使用php和MySQL的理解。问题是当我尝试连接到我的在线数据库时。 如果我写这样的代码:

 define('DB_NAME', 'name');
 define('DB_USER', 'user');
 define('DB_PASS', 'pass!');
 define('DB_HOST', 'localhost');

我没有任何问题。好的,有效! 但是,当我想这样连接时:

 $servername = "localhost";
 $username = "user";
 $password = "pass";
 $dbname = "name";
 $conn = new mysqli($servername, $username, $password, $dbname);

我收到此错误:“拒绝用户访问...”

有人可以帮我解决这个愚蠢的问题吗?

3 个答案:

答案 0 :(得分:0)

此代码适用于两个选项

<?php

//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');


//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);

//Checks for connection
if ($con->connect_error) {
        die("Connection failed: " . $con->connect_error);
}

//If there are no connection, error
if (!$con) {
        die('Could not connect' . mysqli_error());
}

//Select the 'data' database
$con->select_db(DB_NAME);

//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
        echo "Database exists <br>";
} else {
        echo "Database does not exist";
    }

    if($con){

        echo "connection succss";
    }

?>

选项2

<?php

    $servername="localhost";
    $username ="root";
    $password="";
    $dbname="test";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}else{

    echo "connected";
}
?>

这些是我的代码,而且你的用户名/密码也很好,可能有问题

答案 1 :(得分:-1)

这种情况发生了一段时间,因为您更改了数据库的用户名和密码,或者您可以尝试将您的用户设置为root和密码为空。

答案 2 :(得分:-1)

试试这个:

$mysql_host     = 'localhost';
$mysql_user     = 'user';
$mysql_password = 'pass';
$mysql_database = 'localhost';
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_password);
@mysql_select_db($mysql_database);

同时检查该用户的privelges。