dames dames -3 years ago 168
MySQL Question

Using php config file to connect to database instead of PDO connection line

I have the following lines Of code for a database connection, however I would just want to use my include("config.php") Instead of this long line of code, how would i go about doing that

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);

Answer Source

Just make a config.php file, for example consider this file is stored in web root (/var/www/), then the contents of the config.php are like this:

<?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);

?>

then in your other PHP scripts use the include function:

<?php

    include '/var/www/config.php';
    ...

Now in your PHP scripts you can access the $lm object and $dbh object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download