用PHP连接到mysql服务器

时间:2015-05-24 09:37:00

标签: php mysql linux

我可以使用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。

3 个答案:

答案 0 :(得分: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 - &gt;远程mysql然后添加百分比外卡以允许在线访问您的数据库。

答案 1 :(得分:0)

您忘记了数据库名称。

首先在变量

中设置数据库名称
$databaseName = '/* The name of your database */';

试试这个:

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

请参阅documentation

答案 2 :(得分:0)

我发现solution.ssh可以连接到mysql服务器,但httpd无法通过网络连接mysql。我使httpd可以通过网络连接到mysql服务器:

 sudo setsebool -P httpd_can_network_connect=1