php 1脚本链接多个数据库 超时重新建立链接

master.php 主程序
test3.php  持有另一个数据库链接并进行操作的脚本

master.php:

<?php
set_time_limit(0);
if(isset($_SERVER['REMOTE_ADDR'])){
	echo "wrong!";
	exit;
}

require "test3.php";

$dbhost = "192.168.10.44";
$dbuser = "cms";
$dbpw = "ggg";
$dbname = "cms";

$conn = mysql_connect($dbhost, $dbuser, $dbpw) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname,$conn) or die('Could not select database master ');
mysql_query("set names 'utf8'",$conn); 

$test3 = new Test3(); 
for($i=10;$i<=20;$i++){
	
	sleep("20");
	getDbLink($conn);
	$rs = mysql_query("select id,dateline,page_num,top_channel_id from cms_article where id={$i} limit 1 ",$conn);
	$line = mysql_fetch_array($rs);
	echo "master :".$line['id']."\n";	
	$test3->selects();
}
function getDbLink(&$conn){
	global $dbhost, $dbuser, $dbpw,$dbname;
	$rsCheck = mysql_query("set names 'utf8'",$conn);
	if(!$rsCheck){ 
		echo "master reconnect \n";
		mysql_close($conn); // 失去数据库连接,如果要重建连接必须要 关闭原来的资源然后再重新建立
                $conn = '';
		$conn = mysql_connect($dbhost, $dbuser, $dbpw) or die('Could not connect: ' . mysql_error());
		mysql_select_db($dbname,$conn) or die("Could not select database master ".mysql_error());
		mysql_query("set names 'utf8'",$conn); 
	}
	
}
mysql_close($conn);
?>



test3.php :

<?php

class Test3{

	private $dbhost;
	private $dbuser;
	private $dbpw;
	private $dbname;
	private $dbconn;

	public function __construct(){
		
		$this->dbhost = "192.168.44.16";
		$this->dbuser = "root";
		$this->dbpw = 'fhcb!@#$uiop';
		$this->dbname = "ff";
		
		$this->dbconn = mysql_connect($this->dbhost, $this->dbuser, $this->dbpw) or die('Could not connect: ' . mysql_error());
		mysql_select_db($this->dbname,$this->dbconn) or die('Could not select database');
		mysql_query("set names 'utf8'",$this->dbconn); 

	}
	
	// 检查数据库连接如果失去数据库连接则重新建立
	function checkDbLink(){

		$rsCheck = mysql_query("set names 'utf8'",$this->dbconn);
		if(!$rsCheck){ 
			echo "test3 reconnect \n";
			mysql_close($this->dbconn); $this->dbconn = '';
			$this->dbconn = mysql_connect($this->dbhost, $this->dbuser, $this->dbpw) or die('Could not connect test3  : ' . mysql_error());
			mysql_select_db($this->dbname) or die('Could not select database test3');
			mysql_query("set names 'utf8'",$this->dbconn); 
		}
	}
	
	
	public function selects(){
		sleep("20");
		$this->checkDbLink();
		$sqlData = "select p_name  from hs_news_pic order by p_id desc limit 1 ";
		$rs = mysql_query($sqlData,$this->dbconn);
		$line = mysql_fetch_array($rs);
		echo "test3  selects  :".$line['p_name']."\n";
	}
	
	
	
	public function __destruct(){
		mysql_close($this->dbconn);
	}
	
}



?>


注意点: 无论主程序和辅程序 数据库操作 mysql_query,mysql_select_db 等函数一定要加上正确的数据库链接资源句柄参数!

你可能感兴趣的:(PHP)