简体   繁体   English

PHP,无法连接到MySQL服务器

[英]PHP, can't connect to the MySQL server

What might be the reason of the following problem. 可能是以下问题的原因。

PHP function mysql_connect() works fine if I execute it from command line (php -r "mysql_connect('127.0.0.1', 'db_user', 'db_pass');") . 如果我command line (php -r "mysql_connect('127.0.0.1', 'db_user', 'db_pass');")执行它,PHP函数mysql_connect()可以正常工作。

The same call with the same parameters fails for PHP running as an Apache module. 对于具有Apache参数的PHP,具有相同参数的相同调用将失败。

MySQL server is running remotely, connection to it is forwarded using SSH: ssh -fN -L 3306:localhost:3306 remote_host MySQL服务器正在远程运行,使用SSH转发与它的连接:ssh -fN -L 3306:localhost:3306 remote_host

Any ideas what might be wrong? 任何想法可能有什么问题吗?

You'll want to be looking at using MySQLi or PDO as the older MySQL functions are deprecated. 您将要考虑使用MySQLi或PDO,因为不赞成使用旧的MySQL函数。

This should help get you started: 这应该有助于您入门:

<?php
//establish conection
$link = mysqli_connect("host","user","pass","bd") or die("Error: " . mysqli_error($link));

$query = "SELECT name FROM mytable" or die("Error: " . mysqli_error($link));

//execute query
$result = $link->query($query);

//display information
while($row = mysqli_fecth_array($result)) {
  echo $row["name"] . "<br>";
} 
?>

Based on your question and details, I would say that the MySQL server is refusing to connect to your web server (where ever it is) because the connection is not secure (in one fashion or another). 根据您的问题和详细信息,我想说MySQL服务器拒绝连接到您的Web服务器(无论它在哪里),因为连接不安全(以一种或另一种方式)。 If you want to connect via the PHP module in Apache as easily as you do from the command line, set up your connection so that all encryption/ tunneling issues are resolved. 如果要像通过命令行一样轻松地通过Apache中的PHP模块进行连接,请设置连接,以解决所有加密/隧道问题。 That's what I would do. 那就是我会做的。

However, make sure the following line is correct.. 但是,请确保以下行是正确的。

mysql_connect('127.0.0.1', 'db_user', 'db_pass');"

Are you pointing to the correct server? 您是否指向正确的服务器? I thought you said that the MySQL server was remote. 我以为你说过MySQL服务器是远程的。 This line suggests that you are attempting to connect to a local, imaginary MySQL server that is running on the same machine as the web server. 此行表明您正在尝试连接到与Web服务器在同一台计算机上运行的本地虚拟MySQL服务器。 Try getting the IP or domain name of the MySQL server and use that instead (in your web code, that is). 尝试获取MySQL服务器的IP或域名,然后改用它(在您的Web代码中)。

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

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