当我尝试连接到我的数据库时出现以下错误。
警告:mysqli::mysqli() [mysqli.mysqli]: (HY000/2002): 无法通过 /homez.640 中的套接字 '/var/run/mysqld/mysqld.sock' (2) 连接到本地 MySQL 服务器/connelho/www/uea/includes/database.php on line 8 无法连接到 MySQL: (2002) Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
在执行任何 SQl 查询之前,我总是运行以下连接方法:
public static function connect() {
require_once("constants.php");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
die("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
return $mysqli;
}
在任何 SQl 查询之后,我总是运行以下断开连接方法:
public static function disconnect($mysqli = NULL, $stmt = NULL) {
if (isset($mysqli)) {
$mysqli->close();
}
if (isset($stmt)) {
$stmt->close();
}
}
我查看了https://stackoverflow.com/a/2499660并向我的托管服务提供商发送了电子邮件,他们告诉我检查我的脚本“我们有 30 个 MySQL 连接作为限制 - 我们无法调整它,也没有理由这样做如果您的脚本运行正常,应该会发生”。它工作了好几个星期,然后突然停止连接。我是该网站的唯一访问者。
关于我的数据库类如何连接和断开连接的示例:
public static function county_select() {
//connect to database
$mysqli = Database::connect();
//write sql statement
$sql = "SELECT id, county FROM Counties ORDER BY country, county ASC";
//prepared statement, stage 1: prepare
if (!($stmt = $mysqli->prepare($sql))) {
die("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
}
//prepared statement, stage 2: execute
if (!$stmt->execute()) {
die("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
//prepared statement, stage 3: bind result
if (!$stmt->bind_result($id, $county)) {
die("Binding result failed: (" . $stmt->errno . ") " . $stmt->error);
}
$counties = array();
//prepared statement, stage 5: fetch
while ($stmt->fetch()) {
$counties[] = array("id" => $id, "county" => $county);
}
//disconnect from database
Database::disconnect($mysqli, $stmt);
return $counties;
}
我已经一天无法连接到我的网站了。连接多久到期?如何手动断开它们?我认为 PHP 在请求结束时会以任何方式自动关闭数据库连接?