【问题标题】:connect remotly to mysql server with php使用php远程连接到mysql服务器
【发布时间】:2015-05-24 20:38:33
【问题描述】:

我可以通过 ssh 连接到 mysql 服务器。

# mysql -u username -h 185.2.3.80 -ppasword

输出是:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 280
Server version: 5.1.61 Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

我想用php连接mysql服务器:

<?php
$servername = "185.2.3.80";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

这是输出:

Could not connect: Can't connect to MySQL server on '185.2.3.80' (13)

我用 iptables 关闭防火墙并从 my.cnf 中删除 bind-address 和 skip-networking 。但无法连接 php 。

【问题讨论】:

    标签: php mysql linux


    【解决方案1】:

    试试看

    <?php
    $servername = "185.2.3.80:<server Port>";
    $username = "username";
    $password = "password";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    echo "Connected successfully";
    ?>
    

    在我的例子中写下你的服务器端口是 3306。 再做一件事,转到您的 Cpanel -> 远程 mysql,然后添加百分比通配符以允许在线访问您的数据库。

    【讨论】:

    • 我通过删除 bind-address 允许从任何主机访问。所以我可以使用 ssh 连接。
    • 添加端口后是否尝试过?
    【解决方案2】:

    您忘记了数据库名称。

    首先在变量中设置你的数据库名称

    $databaseName = '/* The name of your database */';
    

    试试这个:

    $conn = new mysqli($servername, $username, $password, $databaseName);
    

    参考documentation

    【讨论】:

    【解决方案3】:

    我找到了解决方案.ssh 可以连接到 mysql 服务器,但 httpd 无法通过网络连接 mysql。我使 httpd 可以通过网络连接到 mysql 服务器:

     sudo setsebool -P httpd_can_network_connect=1
    

    【讨论】:

      猜你喜欢
      • 2010-12-28
      • 2013-03-06
      • 2012-04-02
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多