Php 我想将一个服务器数据库连接到另一个服务器

Php 我想将一个服务器数据库连接到另一个服务器,php,mysql,apache,phpmyadmin,Php,Mysql,Apache,Phpmyadmin,我有两个名为server1和server2的服务器。它们都有不同的静态ip地址。我想从server1访问server2数据库。我安装了PHPmyadmin。server1操作系统中的是Ubuntu,server2 fedora12中的 我已经这样做了…mysql错误13即将出现 在server2中,my.cnf包含 [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Default to us

我有两个名为server1和server2的服务器。它们都有不同的静态ip地址。我想从server1访问server2数据库。我安装了PHPmyadmin。server1操作系统中的是Ubuntu,server2 fedora12中的

我已经这样做了…mysql错误13即将出现

在server2中,my.cnf包含

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1

# Disabling symbolic-links is recommended to prevent assorted security risks;
# to do so, uncomment this line:
# symbolic-links=0
# To allow mysqld to connect to a MySQL Cluster management daemon, uncomment
# these lines and adjust the connectstring as needed.
#ndbcluster
#ndb-connectstring="nodeid=4;host=localhost:1186"
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[ndbd]
# If you are running a MySQL Cluster storage daemon (ndbd) on this machine,
# adjust its connection to the management daemon here.
# Note: ndbd init script requires this to include nodeid!
connect-string="nodeid=2;host=localhost:1186"
[ndb_mgm]
# connection string for MySQL Cluster management tool
connect-string="host=localhost:1186"

如果您的问题是连接到远程mysql数据库,则可以尝试以下代码:

$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');

曾经为我工作过

尝试在
server1
上创建一个
connect_server2.php
文件,该文件包含以下内容:

<?
    $server2 = '1.2.3.4'; // the IP of server2
    echo mysql_connect($server2, 'username', 'password') ? 'you have been connected' : 'cannot connect to server2';
?>

首先,您需要在MySql服务器2上启用远程访问

然后,您可以简单地执行以下操作:

mysql_connect("xxx.xxx.xxx.xxx", "username", "password") or die(mysql_error());

这取决于您希望如何访问server2上的数据库

假设您只想通过mysql客户端进行连接,请尝试以下操作:

mysql -h <server2ip or hostname> -u <username> -p 
mysql-h-u-p
在提示下输入密码

如果您想通过php实现这一点,请尝试以下方法,将服务器ip替换为server2的ip,将用户名和密码替换为mysql server2的值:

<?php
$link = mysql_connect('server_ip', 'user', 'password');
 if (!$link) {
die('Error connecting to db: ' . mysql_error());
}
echo 'Successful conntected to database';
mysql_close($link);
?>


如果不出错的话,我认为mysql数据库的端口是必须的!如果没有指定,PHP将连接到默认端口(3306)。但您是对的:始终指定端口。