This visualization is for PDO only, since 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 does not seem to apply to afterall port numbers. If you always use the default port 3306 , then consider removing it from the uri, that is, remove the port=$port; .
If you change ports frequently, consider using the port above for better maintainability with the changes made to the $port variable.
Some probable 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 error below, we are at least closer after changing our connection information:
PDO Exception: SQLSTATE[HY000] [1045] Access denied for user 'GuySmiley'@'localhost' (using password: YES)
After further changes, we are really close, but not quite:
PDO Exception: SQLSTATE[HY000] [1049] Unknown database 'mustard'
From the PDO Connections Guide:
Drew Sep 12 '15 at 8:16 a.m.
source share