3

我无法连接到位于 dotCloud 上的数据库。我试过了:

$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);

$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_name);

$mysqli = new mysqli($remote_server, $db_user, $db_password, $db_name);

$mysqli = mysqli_connect($remote_server, $db_user, $db_password, $db_name);

但它无法连接,我收到“错误 324 (net::ERR_EMPTY_RESPONSE):服务器关闭连接但未发送任何数据。”

我使用以下内容在 mysqli 脚本上方动态检索变量:

$env =  json_decode(file_get_contents("/home/dotcloud/environment.json"));
$db_user = $env->DOTCLOUD_DB_MYSQL_LOGIN;
$db_password = $env->DOTCLOUD_DB_MYSQL_PASSWORD; 
$db_host = $env->DOTCLOUD_DB_MYSQL_HOST;
$db_port = $env->DOTCLOUD_DB_MYSQL_PORT;
$remote_server = '$db_host:$db_port';
//I also define $db_name here
$db_name = 'mydbname';

我在 mysqli 脚本下面还有以下代码:

if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
    $result["status"] = "failed";
    $result["message"] = "Failed to connect to database.";
    echo json_encode($result);
    exit;
} else {
    // Successfully connected!
    $stmt = $mysqli->stmt_init();
    echo "<p>Successfully connected!!</p>";
}

我究竟做错了什么?

4

2 回答 2

12

您的代码中有几处错误。

1.您的 $remote_server 变量使用单引号

$remote_server = '$db_host:$db_port';

这意味着 $remote_server 不会扩展 $db_host 和 $db_port 变量。你应该使用双引号。如果您按原样使用变量,它对您不起作用。

$remote_server = "$db_host:$db_port";

有关更多信息,请参阅此页面: http ://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single

2. 连接时没有使用mysql端口,dotCloud上需要这个,因为它不在标准端口3306上运行mysql。

你的代码:

$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);

正确的代码,使用上面已经声明的变量:

$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port);

更多信息可以在这里找到:http ://www.php.net/manual/en/mysqli.quickstart.connections.php

对于一个完整的示例,它将如下所示。

$env =  json_decode(file_get_contents("/home/dotcloud/environment.json"));
$db_user = $env->DOTCLOUD_DB_MYSQL_LOGIN;
$db_password = $env->DOTCLOUD_DB_MYSQL_PASSWORD; 
$db_host = $env->DOTCLOUD_DB_MYSQL_HOST;
$db_port = $env->DOTCLOUD_DB_MYSQL_PORT;
//I also define $db_name here
$db_name = 'mydbname';

$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "\n";
于 2013-03-04T21:13:33.707 回答
-1
try like this: I think it will help you.

$connect = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$connect) {
    die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';

$db = mysql_select_db($mysql_database,$connect);

if (!$db) echo"'Could not select database";
于 2013-03-02T01:14:13.610 回答