Browse Source

mysqli: add an option enables ping before query

oott123 1 year ago
parent
commit
983d728f31
2 changed files with 21 additions and 0 deletions
  1. 19 0
      classes/db/mysqli.php
  2. 2 0
      include/functions.php

+ 19 - 0
classes/db/mysqli.php

@@ -2,6 +2,11 @@
 class Db_Mysqli implements IDb {
 	private $link;
 	private $last_error;
+	private $host;
+	private $user;
+	private $pass;
+	private $db;
+	private $port;
 
 	function connect($host, $user, $pass, $db, $port) {
 		if ($port)
@@ -9,6 +14,14 @@ class Db_Mysqli implements IDb {
 		else
 			$this->link = mysqli_connect($host, $user, $pass, $db);
 
+		if (MYSQLI_PING_BEFORE_QUERY) {
+			$this->host = $host;
+			$this->user = $user;
+			$this->pass = $pass;
+			$this->db = $db;
+			$this->port = $port;
+		}
+
 		if ($this->link) {
 			$this->init();
 
@@ -26,6 +39,12 @@ class Db_Mysqli implements IDb {
 	}
 
 	function query($query, $die_on_error = true) {
+		if (MYSQLI_PING_BEFORE_QUERY) {
+			if (!mysqli_ping($this->link)) {
+				// if the database connection lost, reconnect before query
+				$this->connect($this->host, $this->user, $this->pass, $this->db, $this->port);
+			}
+		}
 		$result = @mysqli_query($this->link, $query);
 		if (!$result) {
 			$this->last_error = @mysqli_error($this->link);

+ 2 - 0
include/functions.php

@@ -62,6 +62,8 @@
 	define_default('CACHE_MAX_DAYS', 7);
 	// max age in days for various automatically cached (temporary) files
 	define_default('MAX_CONDITIONAL_INTERVAL', 3600*12);
+	// ping before every mysqli queries; this can help to mitigate "MySQL Server has gone away" issues, but may impact performance
+	define_default('MYSQLI_PING_BEFORE_QUERY', false);
 	// max interval between forced unconditional updates for servers
 	// not complying with http if-modified-since (seconds)