gpt4 book ai didi

php - 包含数据库连接错误的 php 文件

转载 作者:行者123 更新时间:2023-11-29 13:27:42 26 4
gpt4 key购买 nike

我想要一个包含所有数据库信息(数据库名、主机、用户名、密码)的通用 php 文件

但是当我在index.php 中包含该页面时,我收到此错误:

用户“apache”@“localhost”的访问被拒绝(使用密码:NO)

连接.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");

在index.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();

公共(public)服务公告

查看 PHP 的 PDO或者最小值(但实际上,只需使用 PDO)mysqli选择。 PHP 的 mysql 扩展安全,您不应该在任何环境中使用它。

关于php - 包含数据库连接错误的 php 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19907495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com