我无法连接到驻留在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>";
}
我做错了什么?
答案 0 :(得分: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";
答案 1 :(得分:-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";