0

I have a problem connecting to my mysql database on another server from my VPS, connecting to localhost mysql works fine. This is my PHP script:

<?php
$servername = "mysql.example.com";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

I am getting this error: SQLSTATE[HY000] [1045] Access denied for user 'username'@'fh24-219.cybersales.cz' (using password: YES)

The problem is propably that host changed from mysql.example.com to fh24-219.cybersales.cz(it points to my VPS ip). I have no idea why. I have already changed httpd_can_network_connect_db and httpd_can_network_connect to 1. I would appreciate some help. I can connect to mysql.example.com with phpmyadmin. Thanks.

J. Doe
  • 17
  • 2
  • 5

2 Answers2

0

Possible, that your $username do not have permissions to connect to database from server, where the PHP script is executed.

Try to create a user with permission to connect from remote server. Execute on MySQL server:

CREATE USER 'testuser'@'fh24-219.cybersales.cz' IDENTIFIED BY 'mypass';

Change 'fh24-219.cybersales.cz' to PHP server IP. If you will write '%' as server IP it will be accessible from anywhere (it is not recommended).

Updated:

If you do not know what permissions user have, execute SHOW GRANTS; on for e.g. PhpMyAdmin to see if remote IP is mentioned.

Aurimas
  • 644
  • 5
  • 11
  • Thanks for your help, but I have acess to only one user, which doesn't have enough privilages to create new user. Do you think that my database hosting disabled remte acess to my database? – J. Doe Dec 09 '17 at 10:13
  • Connect to database with PhpMyAdmin and execute: SHOW GRANTS; What hosts are mentioned for user? – Aurimas Dec 09 '17 at 10:54
  • Only localhost was mentioned. Thanks for your help, I've transfered database to my vps. – J. Doe Dec 10 '17 at 13:04
-1

Had the same problem, try changing the connection from:

new PDO("mysql:host=$servername;dbname=database", $username, $password);

to

new PDO("mysql: host=$servername;dbname=database", $username, $password);

Note the space between mysql: and host. It worked for me, can't guarantee you will not get access denied on the @localhost version of the account (I am stuck at this point) but it removes the trailing bit.

  • This doesn't work and also lacks any explanation or logic. Please try to post logical explanations – BK7 Nov 16 '18 at 06:07