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.
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 eg PhpMyAdmin to see if remote IP is mentioned.
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.
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.