简体   繁体   English

为什么在连接到远程托管的mysql数据库时,php PDO使用的主机名不同于mysql_connect()所使用的主机名?

[英]Why php PDO uses a different from hostname to the one used by mysql_connect() when connecting to a remotely hosted mysql database?

I've mysql database and php/apache on two different servers: let's say hostphp.domain.com and hostmysql.domain.com. 我在两个不同的服务器上都有mysql数据库和php / apache:假设hostphp.domain.com和hostmysql.domain.com。

On the mysql server I've set a user "my_user" with permissions to connect to "my_database" db from the specific host "hostphp.domain.com". 在mysql服务器上,我设置了一个用户“ my_user”,该用户具有从特定主机“ hostphp.domain.com”连接到“ my_database”数据库的权限。

When I connect to it using mysql_connect it does right. 当我使用mysql_connect连接到它时,它运行正常。 But when I do it via php PDO I get this error: 但是,当我通过php PDO进行操作时,出现此错误:

SQLSTATE[42000] [1044] Access denied for user 'my_user'@'%' to database 'my_database'

I've done some tests and I found the problem is ...@'%', mysql is refusing that connection because "my_user" does not have permission to connect from any host. 我已经做了一些测试,发现问题是... @'%',mysql拒绝了该连接,因为“ my_user”没有从任何主机进行连接的权限。

Also I've tried to connect using mysql_connect with a wrong password to see the error and I get this: 我也尝试使用mysql_connect和错误的密码进行连接以查看错误,我得到了:

Could not connect: Access denied for user 'my_user'@'hostphp.domain.com' (using password: YES).

The difference is in ..@'%' and ...@'hostphp.domain.com'. 区别在于.. @'%'和... @'hostphp.domain.com'。

So that's my question, why php pdo do not declare hostname when connecting to a remote host? 这就是我的问题,为什么在连接远程主机时php pdo不声明主机名? (or is doing that wrong). (或者做错了)。

Thanks and sorry for my english. 谢谢你,我的英语不好意思。

Edit. 编辑。 Some code example, this does not work: 一些代码示例,这不起作用:

try {
    $pdo = new PDO(
        'mysql:host=hostmysql.domain.com;port=3306;dbname=my_database',
        'my_user',
        'my_pass'
    );
} catch (PDOException $e) {
    die($e->getMessage());
}

but this works ok: 但这行得通:

$conn = mysql_connect('hostmysql.domain.com', 'my_user', 'my_pass');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
} 

You have successfully connected to the host using mysql_connect, but you got no errors because you did not attempt to select the database. 您已经使用mysql_connect成功连接到主机,但是没有出现错误,因为您没有尝试选择数据库。

Your user probably doesn't have access to your database. 您的用户可能无权访问您的数据库。

Try running mysql_select_db("my_database"); 尝试运行mysql_select_db(“ my_database”); after connected to the host and you should get the same error. 连接到主机后,您应该会得到相同的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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