文章主要介紹了php使用MySQL儲存session會話的方法,涉及php操作session及資料庫的相關技巧,需要的'朋友可以參考下。
本文例項講述了php使用MySQL儲存session會話的方法。分享給大家供大家參考。具體分析如下:
在很多大的系統中一般都有這個功能,但是要分離出來分析,網上的資料也不太多 這裡我整理了一篇發出來與大家分享
使用MySQL儲存session會話較files有很多優點:
1) 有利於分佈式系統,files只能儲存在一臺機器上
2) 有利於大訪問量的系統,使用files時每個session儲存在一個檔案中,目錄會超級大,查詢session檔案會比較困難。
使用MySQL儲存會話首先要建立session表:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
$hostname_login = "localhost"; // Server address
$username_login = "root"; // User name
$password_login = ""; // Password
//
$data_name = "session"; // Database name
$login = mysql_pconnect($hostname_login, $username_login, $password_login) or trigger_error(mysql_error(),E_USER_ERROR);
$sql="SHOW DATABASES LIKE '".$data_name."'"; // If it is exist
if($rs_table=mysql_query($sql,$login)) {
if($rs_value=mysql_fetch_array($rs_table)) {
echo "資料庫已經存在!n!";
exit();
}
}
$sql="CREATE DATABASE $data_name";
mysql_query($sql); // Crate database
echo "資料庫建立成功!n";
mysql_select_db($data_name, $login);
$sql="CREATE TABLE `sessions` (
`SessionKey` varchar(32) NOT NULL default '',
`SessionArray` blob NOT NULL,
`SessionExpTime` int(20) unsigned NOT NULL default '0',
PRIMARY KEY (`SessionKey`),
KEY `SessionKey` (`SessionKey`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8"; //新建資料庫 sql語句
mysql_query($sql);
echo "成功新建資料庫表!";
?>
MysqlSession 類如下:
?