gpt4 book ai didi

php - PDO:数据库离线时连接超时

转载 作者:行者123 更新时间:2023-11-29 01:54:43 25 4
gpt4 key购买 nike

我有一个使用 PDO 连接到外部数据库的网站。

好的,一切正常。

唯一的问题是当数据库离线时。我刷新网站,浏览器加载找到的第一个查询,但加载它需要 30+ 秒,当完成页面停止加载时(因为有一个 exit(); 连接时的功能失败)并出现此错误:

SQLSTATE[HY000] [2002] Connection timed out

我希望网站在数据库离线时可以正常访问,因为它离线是例行公事,但存在连接超时和页面加载时间超过 30 秒的问题.

我该如何解决这个问题?

这是我进行连接和查询的方式:

class.db.php

<?php
class db
{
private $db = NULL;
private $host = NULL;
private $user = NULL;
private $password = NULL;
private $port = NULL;

public function __construct($host, $user, $password, $port) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->port = $port;
}

private function initDb() {
if($this->db == NULL) {
try {
$this->db = new PDO('mysql:port='.$this->port.';host='.$this->host, $this->user, $this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $error) {
echo '<b>An error occured!</b><br />' . $error->getMessage();
exit();
}
}
}

public function query($array) {
$this->initDb();
$sql = $array['sql'];
$par = (isset($array['par'])) ? $array['par'] : array();
$ret = (isset($array['ret'])) ? $array['ret'] : 'res';
$obj = $this->db->prepare($sql);
$result = $obj->execute($par);
if (!$result) exit("Errore Query");
switch ($ret) {
case 'fetch-assoc':
return $obj->fetch(PDO::FETCH_ASSOC);
break;

case 'fetch-all':
return $obj->fetchAll(PDO::FETCH_ASSOC);
break;

case 'fetch-column':
return $obj->fetchColumn();
break;

case 'result':
return $result;
break;

default:
return $result;
break;
}
}

public function __destruct() {
$this->db = NULL;
}
}

用法(我如何运行查询)

require_once ROOT . 'include/class.db.php';

$config['db']['servername'] = ""; // Database IP
$config['db']['username'] = ""; // Database Username
$config['db']['password'] = ""; // Database Password
$config['db']['port'] = 3306; // Database Port

$db = new db($config['db']['servername'], $config['db']['username'], $config['db']['password'], $config['db']['port']);

// Example of a query

$data = $db->query(array(
'sql' => "SELECT count(*) FROM player.player WHERE DATE_SUB(NOW(), INTERVAL 1 DAY) < player.last_play",
'ret' => 'fetch-column'
));

echo $data;

感谢您的帮助。

最佳答案

你可以设置超时属性:

private function initDb() {
if($this->db == NULL) {
try {
$this->db = new PDO('mysql:port='.$this->port.';host='.$this->host, $this->user, $this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_TIMEOUT, 5); //Add this.
}
catch (PDOException $error) {
echo '<b>An error occured!</b><br />' . $error->getMessage();
exit();
}
}
}

这将使查询在 5 秒后超时,而不是您在问题中描述的 30 秒。请注意,底层的 mysql 引擎必须支持它,因为并非所有引擎都支持它。

关于php - PDO:数据库离线时连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32320222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com