Tiffany Tiffany - 1 year ago 48
MySQL Question

Is it possible to set up a PDO DB connection using variables defined in another file? PHP

So, I have a config.php file with

define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_USER', 'database_user');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');

When I am defining my PDO connection, am I able to use this?

$dbh = new PDO("mysql:host=DB_HOST;dbname=DB_NAME;charset=utf8", "DB_USER", "DB_PASS");

I saw this question: Setting up a db connection using variables from another file which is similar, but it's using mysqli_connection, and I'm not sure how different that is from PDO, so I'm not certain if the answer solves my question.

If I'm not able to use the defined variables from my config.php file, should I define them locally in my file using:

$db_host = DB_HOST;
$db_user = DB_USER;

and so on...

Or am I using the PDO connection with the config.php defined variables incorrectly? If so, how should I be doing it?

The error I'm receiving when I try to run my webpage says that it cannot connect to the database host (php_network_getaddresses: getaddrinfo failed: No such host is known.) which I assume my PDO connection defined variables are the culprit.

Answer Source

You can use them as constants, but including them in a string like that will make it think they're strings, not constants. You can modify your connection like this:

$dbh = new PDO("mysql:host={DB_HOST};dbname={DB_NAME};charset=utf8", DB_USER, DB_PASS);


$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8", DB_USER, DB_PASS);