包括带有数据库连接错误的 php 文件


Including php file with database connection error

我想要一个包含所有数据库信息(dbname,host,username,password)的通用php文件。

但是当我在类似的索引中包含页面时.php我收到此错误:

拒绝用户"apache"@"localhost"的访问(使用密码:否)

连接.php

<?php
class dbconnect{
    private $host = '**'; 
    private $user = '**';
    private $pass = '**';
    public $con;
function Connect($db = '**') {
    if($db=='**'){
        $this->host="localhost";
        $this->user="**";
        $this->pass="**";
        $db="**";
    }else{
                $this->host="**";
                $this->user="**";
                $this->pass="**";
    }
    $this->con = mysql_connect($this->host,$this->user,$this->pass);
    if (!$this->con)
      {
        die('Could not connect: ' . mysql_error());
      }
    $blaa = mysql_select_db($db, $this->con);
    mysql_query("SET NAMES UTF8");
    return $blaa;
}
function Disconnect() {
    //$this->con = mysql_connect($this->host,$this->user,$this->pass);
    mysql_close();
}
}
?>

我确定**信息是正确的,因为当我将其指定为:

$con=mysqli_connect("example.com","example","password","my_db");

在索引中.php它有效

需要注意的是,您的测试用例实际上并不能证明它有效。

这输出什么:

$conn = mysql_connect("example.com", "user", "password");
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}

因为如果没有它,您不一定会得到失败的信息。

最重要的是,出于调试目的,让我们稍微简化一下您的类:

class dbconnect
{
    private $host = '**';
    private $user = '**';
    private $pass = '**';
    public $con;
    public function Connect($host = "localhost", $user = "root", $pass = "")
    {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->con = mysql_connect($this->host, $this->user, $this->pass);
        if (!$this->con) {
            die('Could not connect: ' . mysql_error());
        }
        $blaa = mysql_select_db($db, $this->con);
        mysql_query("SET NAMES UTF8");
        return $blaa;
    }
    public function Disconnect()
    {
        mysql_close($this->con);
    }
}

现在当你这样做时你会得到什么

$db = new dbconnect("example.com", "user", "password");

请确保使用的是有效的凭据,并且不会通过这些方法遇到默认值或不正确的变量分配等问题。

现在,如果您不想提供这些值,您可以简单地:

$db = new dbconnect();

公益广告

查看PHP的PDO或至少(但实际上,只需使用PDO)mysqli替代方案。PHP 的 mysql 扩展并不安全,你永远不应该在任何环境中使用它。

如果连接信息正确,请检查 MySQL 用户的主机访问权限:

SELECT user, host FROM mysql.user

如果设置了"localhost",则用户只能在本地访问数据库,否则"%"将打开访问。

通常是连接凭据的问题。

检查您是否可以使用为该网站设置的详细信息登录您的 mysql。

MySQL -u Apache -P

然后它会要求您输入密码。

如果该登录不起作用,则您的mysql帐户有问题。

您使用了不正确的参数进行访问。只需转储行$this->con = mysql_connect($this->host,$this->user,$this->pass);的变量。您可以使用调试器或回显打印指令。

此外,使用PDO扩展访问数据库。更好!为什么我不应该在 PHP 中使用 mysql_* 函数?