Your database_connection() function does not receive connection variables in the correct scope, so they are not set when you try to connect and therefore are passed as NULL , and PDO by default sets the connection host to localhost .
Pass them as function parameters:
// Defined at global scope... $db_host = "..."; $db_name = "..."; $db_user = "..."; $db_pass = "..."; // Pass the 4 variables as parameters to the function, since they were defined at global // scope. function database_connection($db_host, $db_name, $db_user, $db_pass) { try { $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass); } // Called as: $pdo = database_connection($db_host, $db_name, $db_user, $db_pass);
If you use only these variables inside the connection function and do not need them elsewhere, consider their definition in the scope of the function, which will save you from passing them as parameters.
function database_connection() { // Only needed here, so define in function scope $db_host = "..."; $db_name = "..."; $db_user = "..."; $db_pass = "..."; try { $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass); }
The ultimate and often least desirable option is to define the variables in the global scope as you did, but access them via $GLOBALS[] (or the global ) in a function:
function database_connection() { try { $pdo = new PDO("mysql:host={$GLOBALS['db_host']};dbname={$GLOBALS['db_name']}", $GLOBALS['db_user'], $GLOBALS['db_pass']); }
Note that if you are working with error_reporting and display_errors , as it should be, you will see undefined variable notifications.
error_reporting(E_ALL); ini_set('display_errors', 1);