The error means your PHP cannot find the host where MySQL server is supposed to be. Please check if hostname is correct.
Reading the error message attentively always helps. As you can see from
the stack trace, namely the __construct('mysql:host=port...',
part, the hostname used begins from the word "port", which doesn't seem to be a valid hostname. Try to use 127.0.0.1
if MySQL is located on the same computer or a correct hostname if it's on some other host.
Note that you should never do anything like try {...} catch(...) {echo "Connection failed: " . $e->getMessage();}
as suggested in the other answer. As it will display only the php_network_getaddresses: getaddrinfo failed
message but won't provide a clue with incorrect hostname or other important details. Always leave the PDOException alone.
A minimalistic correct example for connecting MySQL would be like this.
First, create a file database_config.php
that only contains the database credentials, as they are going to be different on each host
<?php
$db_host = '127.0.0.1';
$db_name = 'your database name'
$db_user = 'your username';
$db_pass = 'your password';
$db_port = '3306'; // or the actual port if it's different
then create the database_connection.php
file like this
<?php
require __DIR__."/database_config.php";
$dsn = "mysql:host=$db_host;dbname=$db_name;port=$db_port;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $db_user, $db_pass, $options);
and then include this file in any script that needs a database connection.
Note that on a live server you must configure the PHP's display_errors
option to off
, so database errors won't be displayed to the end users. Instead, configure the log_errors
option to on
so the errors will be logged instead.