php将简单的数据从数据库,php将session保存到数据库的简单示例

这篇博客展示了如何在PHP中将session数据保存到MySQL数据库。通过创建`sessions`表并设置相应的字段,然后定义session的读写、开始、结束、销毁和垃圾回收等操作,实现了session数据的持久化存储。示例代码详细说明了每个函数的功能,包括插入、更新session数据以及删除过期session。
摘要由CSDN通过智能技术生成

/**

* PHP中将session保存到数据库的代码

*

* @param

* @arrange 512-笔记网: 512Pic.com

**/

// 'sessions' table schema

// create table sessions (

// session_id char(32) not null,// session_data text not null,// session_expiration int(11) unsigned not null,// primary key (session_id));

//

include_once 'DB.PHP';

// Global Variables

$dbh = NULL;

function on_session_start ($save_path,$session_name) {

global $dbh;

$dbh = DB::connect('MysqL://user:secret@localhost/SITE_SESSIONS',true);

if (DB::isError($dbh)) {

die(sprintf('Error [%d]: %s',$dbh->getCode(),$dbh->getMessage()));

}

}

function on_session_end ()

{

// Nothing needs to be done in this function

// since we used persistent connection.

}

function on_session_read ($key)

{

global $dbh;

$stmt = "select session_data from sessions";

$stmt .= " where session_id = '$key'";

$stmt .= " and session_expiration > now()";

$sth = $dbh->query($sth);

$row = $sth->fetchRow(DB_FETCHMODE_ASSOC);

return $row['session_data'];

}

function on_session_write ($key,$val)

{

global $dbh;

$val = addslashes($val);

$insert_stmt = "insert into sessions values('$key','$val',now() + 3600)";

$update_stmt = "update sessions set session_data = '$val',";

$update_stmt .= "session_expiration = now() + 3600 ";

$update_stmt .= "where session_id = '$key'";

// First we try to insert,if that doesn't succeed,it means

// session is already in the table and we try to update

if (DB::isError($dbh->query($insert_stmt)))

$dbh->query($update_stmt);

}

function on_session_destroy ($key)

{

global $dbh;

$stmt = "delete from sessions where session_id = '$key'";

$dbh->query($stmt);

}

function on_session_gc ($max_lifetime)

{

global $dbh;

// In this example,we don't use $max_lifetime parameter

// We simply delete all sessions that have expired

$stmt = "delete from sessions where session_expiration < now()";

$dbh->query($stmt);

}

session_start ();

// Register the $counter variable as part

// of the session

session_register ("counter");

// Set the save handlers

session_set_save_handler ("on_session_start","on_session_end","on_session_read","on_session_write","on_session_destroy","on_session_gc");

// Let's see what it does

$counter++;

print $counter;

session_destroy();

/*** 来自编程之家 jb51.cc(jb51.cc) ***/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值