gpt4 book ai didi

php - 通过代码将 PHP 连接到 MySQL

转载 作者:行者123 更新时间:2023-11-29 06:18:54 24 4
gpt4 key购买 nike

我有一个用于配置数据库和构造函数的 .ini 文件,如下所示:

function PHPRestSQL($iniFile = 'phprestsql.ini') {

$this->config = parse_ini_file($iniFile, TRUE);

if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER['REQUEST_METHOD'])) {

if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
$this->requestData = '';
$httpContent = fopen('php://input', 'r');
while ($data = fread($httpContent, 1024)) {
$this->requestData .= $data;
}
fclose($httpContent);
}

$urlString = substr($_SERVER['REQUEST_URI'], strlen($this->config['settings']['baseURL']));
$urlParts = explode('/', $urlString);

$lastPart = array_pop($urlParts);
$dotPosition = strpos($lastPart, '.');
if ($dotPosition !== FALSE) {
$this->extension = substr($lastPart, $dotPosition + 1);
$lastPart = substr($lastPart, 0, $dotPosition);
}
array_push($urlParts, $lastPart);

if (isset($urlParts[0]) && $urlParts[0] == '') {
array_shift($urlParts);
}

if (isset($urlParts[0])) $this->table = $urlParts[0];
if (count($urlParts) > 1 && $urlParts[1] != '') {
array_shift($urlParts);
foreach ($urlParts as $uid) {
if ($uid != '') {
$this->uid[] = $uid;
}
}
}

$this->method = $_SERVER['REQUEST_METHOD'];

}
}

构造函数设置后,会尝试通过connect方法连接数据库

 function connect() {
$database = $this->config['database']['type'];
require_once($database.'.php');
$this->db = new $database();
if (isset($this->config['database']['username']) && isset($this->config['database']['password'])) {
if (!$this->db->connect($this->config['database'])) {
trigger_error('Could not connect to server', E_USER_ERROR);
}
} elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$this->config['database']['username'] = $_SERVER['PHP_AUTH_USER'];
$this->config['database']['password'] = $_SERVER['PHP_AUTH_PW'];
if (!$this->db->connect($this->config['database'])) {
$this->unauthorized();
exit;
}
} else {
$this->unauthorized();
exit;
}
}

这是我的 .ini 文件配置的一部分:

[database]
type = "mysql"
;type = "postgresql"
server = "neighborme.db.7346057.hostedresource.com"
database = "neighborme"
;username = "dbusername"
;password = "dbpassword"
foreignKeyPostfix = "_uid"

我在 .ini 文件中做错了什么导致它无法连接吗?

为什么这个 if 语句没有返回 true:

if (isset($this->config['database']['username']) && isset($this->config['database']['password']))

最佳答案

嗯...可能是因为您在 ini 文件中注释掉了用户名?

尝试将 ;username = "dbusername" 更改为 username = "dbusername"

说实话,我并没有真正看太多代码的其余部分,因为它太多了。也许您可以尝试将其简化为重现问题所需的基本部分?

但是我上面提到的只是我第一眼看到的

关于php - 通过代码将 PHP 连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788629/

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