我正在使用一个config.php文件来模拟一些东西,我试图把我的mysql凭据放在那里,然后在另一个文件中使用它们,但是它没有传递值,
有什么能帮我找到解决办法吗。
代码config.php:
/* Database credentials*/
$dbHost = 'localhost';
$dbName = 'xx';
$dbUsername = 'xx';
$dbWachtwoord = 'xx';
代码dbconnect.php:
<?php include 'config.php';
class Database
{
private $host;
private $db_name;
private $username;
private $password;
public $conn;
public function dbConnection()
{
$this->host = $dbHost;
$this->db_name = $dbName;
$this->username = $dbUsername;
$this->password = $dbWachtwoord;
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
class.user数据库连接:
<?php
require_once('config.php');
require_once('dbconnect.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
提前感谢=)
3条答案
按热度按时间kgsdhlau1#
您可以尝试以下代码:
配置.php
用户类
数据库连接.php
x6492ojm2#
与其将其视为传递变量,不如将其视为传递配置。数据库类必须知道这些配置选项才能使用。换句话说:一旦你创建了一个类数据库示例,它就应该被配置好并且可以使用,就像任何服务一样。我强烈建议您遵循将配置作为依赖项注入的规则。
ymdaylpp3#
在类中包含'config.php'