简体   繁体   中英

PHP PDO connection to MySQL fails, mysql_connect works fine

I'm trying to connect to remote MySQL database using PDO, but it fails with error:

Connection failed: SQLSTATE[28000] [1045] Access denied for user 'my_user'@'some.ip.address' (using password: YES)

This is how I'm trying to connect:

$dsn = "mysql:host=sql.my_domain.nazwa.pl;dbname=my_db;port:3307";
$user = "my_user";
$password = "my_password";

try {
    $this->db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

and it fails. But this way:

mysql_connect('sql.my_domain.nazwa.pl:3307', 'my_user', 'my_password');

works fine.

Anyone have any idea what can be wrong with PDO, its configuration, parameters I set or maybe this specific server (nazwa.pl)?

[SOLVED] Ok, so that was simple (but also tricky to notice...) syntax error, it should be a = instead of : in port part of dsn .

Try replacing:

$dsn = "mysql:host=sql.my_domain.nazwa.pl;dbname=my_db;port:3307";

with

$dsn = "mysql:host=sql.my_domain.nazwa.pl;dbname=my_db; port=3307";

If you are trying to connect to database on some other server Make sure your Sql server gives you the access on the particular port in your case 3307 from the IP address of the places where your codes are hosted. If the both the servers are same try with localhost or 127.0.0.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM