This is a PDO-only visualization, as the mysql_*
library is deprecated.
<?php
// Begin Vault (this is in a vault, not actually hard-coded)
$host="hostname";
$username="GuySmiley";
$password="thePassword";
$dbname="dbname";
$port="3306";
// End Vault
try {
$dbh = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "I am connected.<br/>";
// ... continue with your code
// PDO closes connection at end of script
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
?>
Note that this OP Question appeared not to be about port numbers afterall. If you are using the default port of 3306
always, then consider removing it from the uri, that is, remove the port=$port;
part.
If you often change ports, consider the above port usage for more maintainability having changes made to the $port
variable.
Some likely errors returned from above:
PDO Exception: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
PDO Exception: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
In the below error, we are at least getting closer, after changing our connect information:
PDO Exception: SQLSTATE[HY000] [1045] Access denied for user 'GuySmiley'@'localhost' (using password: YES)
After further changes, we are really close now, but not quite:
PDO Exception: SQLSTATE[HY000] [1049] Unknown database 'mustard'
From the Manual on PDO Connections: