我有以下数据库连接的代码行,但是我只想使用我的include(“config.php”)而不是这么长的代码行,我将如何去做
try {
$dbh = new PDO('mysql:host=localhost;dbname=lms;charset=UTF-8', 'root', 'password');
}
catch (PDOException $e) {
die('unable to connect to database ' . $e->getMessage());
}
// create LM object, pass in PDO connection
$lm = new lazy_mofo($dbh);
答案 0 :(得分:4)
只需创建一个config.php文件,例如考虑将此文件存储在web根目录(/var/www/
)中,然后config.php的内容如下:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=lms;charset=UTF-8', 'root', 'password');
}
catch (PDOException $e) {
die('unable to connect to database ' . $e->getMessage());
}
// create LM object, pass in PDO connection
$lm = new lazy_mofo($dbh);
?>
然后在您的其他PHP脚本中使用include
函数:
<?php
include '/var/www/config.php';
...
现在,在PHP脚本中,您可以访问$lm
对象和$dbh
对象。
答案 1 :(得分:1)
例如include("config.inc.php")
和config.inc.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=lms;charset=UTF-8', 'root', 'password');
}
catch (PDOException $e) {
die('unable to connect to database ' . $e->getMessage());
}
$lm = new lazy_mofo($dbh);
?>
答案 2 :(得分:1)
你可以在你的包含文件中创建一个db包装器类,并且对它非常懒惰=)
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'lms');
define('DB_USER', 'root');
define('DB_PASS', 'password');
class Database{
public function __construct() {
$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
$o = new Database();
答案 3 :(得分:-1)
我的连接PDO
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "db");
try {
$db = new PDO("mysql:host=" . DB_HOST . ";charset=utf8mb4;dbname=" . DB_NAME, DB_USER, DB_PASS);
/* set the PDO error mode to exception */
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}