我是pdo和课程的新手。如果我手动编写数据库信息,我使用此代码连接到数据库。但我想从具有4行的文本文件中读取所有这些信息。我在下面使用此代码,但有些错误。
$sqlsrv_txt = "evrak_tip.txt";
$satirlar = file($sqlsrv_txt);
$host = substr($satirlar[0], strpos($satirlar[0], ":") + 1);
$db_name = substr($satirlar[1], strpos($satirlar[1], ":") + 1);
$username = substr($satirlar[2], strpos($satirlar[2], ":") + 1);
$password = substr($satirlar[3], strpos($satirlar[3], ":") + 1);
class Database
{
private $host = "HOST NAME";
private $db_name = "DB NAME";
private $username = "USER NAME";
private $password = "PASSWORD";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("sqlsrv:server=" . $this->host . ";Database="
.$this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING,
PDO::SQLSRV_ENCODING_UTF8);
}
catch(PDOException $e)
{
echo "Connection error: " . $e->getMessage();
}
return $this->conn;
}
}
正如您在代码中看到的,我需要将来自txt文件的变量写入host,db_name,username和password accoridng。
有人可以帮我这个吗?
答案 0 :(得分:0)
我通过创建和读取ini文件来修复它。
$config = parse_ini_file("config.ini");
$this->conn = new
PDO($config['type'].":server=".$config['host'].";Database=".$config['dbname'],
$config['user'], $config['password']);