Connection script can't connect to DB

Problem with my connection script: It wont connect to DB. Why?
Error message in the bottom.

define("host",'');  // Default database host.
define("dbname", 'mydbname');   // Default database name.
define("username",'myusername');	// Deafault database username .
define("password",'mypassword');		    // Default database password.

function pdoConnect($dbname=database)
    $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $db;
try {
$pdo = new PDO(';mydbname=mydb', 'myusername',
$output = 'Database connection established.';
catch (PDOException $e) {
$output = 'Unable to connect to the database server: ' . $e->getMessage();

This is the ERROR message printed out on screen. Why?:
Unable to connect to the database server: SQLSTATE[HY000] [2002] Connection refused

This error can occur for several reasons, such as:

The MySQL server is not running on the specified host or port.
The MySQL server is not configured to allow connections from the client's IP address.
The MySQL user specified does not have permission to access the specified database.
There is a network issue preventing the client from connecting to the MySQL server.

You should check the database server configuration and make sure that the host, port, username, password, and database name are correct. Additionally, ensure that the MySQL server is running, and that the necessary ports are open in the firewall. If you are still having trouble, try connecting to the MySQL server using a MySQL client tool to see if the issue is with your code or with the server itself.

In short your PDO connection is inside of a function…get it out of the function.


$host = 'localhost'; // your database host
$dbname = 'mydatabase'; // your database name
$username = 'myusername'; // your database username
$password = 'mypassword'; // your database password

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    // set additional PDO attributes if needed
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();


Sponsor our Newsletter | Privacy Policy | Terms of Service