如何在php中使用conf文件

时间:2013-09-05 04:40:15

标签: php mysql

我试图通过仅包含conf.php来避免硬编码,这将包含我需要的变量/值

我怎样才能做到这一点?

这是 conf.php

的代码
<?php
mysql_connect("localhost", "tiger","tiger") or die (mysql_error ());
mysql_select_db("theaterdb") or die(mysql_error());
?>

其他 PHP 页面的编码如下:

$q = strtolower(trim($_GET["q"]));

try {
    $dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$sql = 'SELECT address FROM theater WHERE LOWER(theater_name) = :q';

$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
$sth->execute();

而不是这一行:

dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');

我想使用conf.php文件。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

//在每个其他页面中包含conf.php

conf.php

<?php
    try {
        $dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
?>

other_page.php

<?php
    include("conf.php");

    $q = strtolower(trim($_GET["q"]));

    $sql = 'SELECT address FROM theater WHERE LOWER(theater_name) = :q';

    $sth = $dbh->prepare($sql);
    $sth->bindValue(':q', $q);
    $sth->execute();

?>