Troy Cosentino Troy Cosentino - 2 months ago 7x
MySQL Question

PDO to connect to web sql from localhost?

I am trying to do some testing, i am using MAMP and trying to connect to my SQL database on my server. I haven't used PDO before and am having a hard time tracking down what error codes mean what. I am getting this:

SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'hostname' (60)

My connection function:

function getConnection() {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
return $dbh;

where i am trying to perform the query:

function getTypes() {
$sql = "SELECT id, name FROM type";
try {
$db = getConnection();
$stmt = $db->query($sql);
$types = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"wine": ' . json_encode($types) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
echo 'getTypes';

Edit: I can connect using the same credentials with mysqli.


It's a security problem. To avoid your database beeing flooded or filled with garbage a configuration setting says "only local ip can access to the database". All shared hosting do that and it is a good practice to do it if you have a dedicated server.

in /var/mysql/my.conf on linux you have got something like that :

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            =