最近遇到了一個非常奇怪的問題,php往mysql中讀寫資料,過一天就不work了.一直不能求解,指導有一天,有人對我說mysql 連接配接可能會逾時.
google了一下,發現mysql connection預設的逾時時間為8小時.當時我想讓我的這個連接配接永久不逾時,該怎麼辦呢?
有人說在mysql配置檔案my.cfg中[mysqld]中添加
wait _timeout =31536000 (這裡的這個數字的機關是秒,31536000秒=365天,這也是可設定的最大值)
這個解決辦法不是最好的,因為這個"一年" != 永久..如何才能讓該連接配接永久不逾時呢?
然後,我繼續google....
最後找到了我需要的答案,非常優雅的方式:
Php代碼

- function reconnect(){
- if (!mysql_ping ($this->db)) {
- //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
- mysql_close($this->db);
- $this->connect();
- }
- }
其中的mysql_ping()用來判斷連接配接是否已經被斷開了,若是斷開了,關閉目前的連結,重新建立新的連接配接.
這樣,隻要發現連接配接被斷開了,即可重新連接配接了.
參考: http://php.net/manual/en/function.mysql-ping.php
【轉自】http://jinchishuxue.iteye.com/blog/1115148