我可以在命令行中远程连接到mySQL数据库,但不能使用php脚本

时间:2013-09-25 18:30:54

标签: php mysql remote-connection

错误: 致命错误:未捕获异常'PDOException',消息'SQLSTATE [28000] [1045]访问被拒绝用户'tech'@'localhost'(使用密码:YES)'在.......

我能够在命令行远程连接,但不能使用php,任何想法在哪里看?

以下是详细信息:

Webserver A:1.1.1.1拥有php脚本:     

$REGIS_DB_SERVER = "2.2.2.2"; //I've tried the IP as well as "pretendhostname.com"
$REGIS_DB_NAME = "db_name";
$REGIS_DB_USER = "tech"; // or any other user name
$REGIS_DB_PASSWORD = "password";

//connect to db
$db = new PDO("mysql:host = $REGIS_DB_SERVER; dbname=$REGIS_DB_NAME; charset=utf8", $REGIS_DB_USER, $REGIS_DB_PASSWORD);
print_r($db -> errorInfo());
echo "Connected<br>";

$sql = "CREATE TABLE Test(PersonID int,LastName varchar(255),FirstName varchar(255),Address varcha(255),City varchar(255))";
$result = $db->query($sql);

echo "$result <br>";

?>

Webserver B:2.2.2.2拥有mySQL数据库: 运行Ubuntu 11.04

/etc/mysql/my.cnf

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#Commented out to allow remote connections to this database
#bind-address           = 216.70.81.240

我运行mysql> select Host,User from user;并获取:

+-----------------------+------------------+
| Host                  | User             |
+-----------------------+------------------+
| %                     | root             |
| 127.0.0.1             | root             |
| 1.1.1.1               | tech             |
| localhost             | debian-sys-maint |
| localhost             | root             |
| localhost             | tech             |
+-----------------------+------------------+

Open Port 3306 in ubuntu 12.04 to allow connections to mysql from any ip意味着它不是iptable问题并且测试连接:

我进入了Webserver A 1.1.1.1并运行:

mysql -u tech -p -h 2.2.2.2
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 200672
Server version: 5.1.63-0ubuntu0.11.04.1 (Ubuntu)

3 个答案:

答案 0 :(得分:1)

找到后: PDO cannot connect remote mysql server 我意识到如果主机不被理解&#34;,PDO连接将默认为host = localhost。仔细观察,我意识到作业之间有两个空格。我没有意识到语法中的空格。

所以最后,这是一个语法错误:

工作解决方案(删除空格):

$db = new PDO("mysql:host=$REGIS_DB_SERVER; dbname=$REGIS_DB_NAME; charset=utf8", $REGIS_DB_USER, $REGIS_DB_PASSWORD);

答案 1 :(得分:1)

您需要禁用SELinux,以运行以下CMD

setsebool httpd_can_network_connect = 1

答案 2 :(得分:0)

这绝对是数据库权限/权限问题。问问你的DBA /对的SysAD GRANT privileges为您的本地服务器访问数据库