php将session 用数据库存储时出错

错误1:Warning: session_start(): Failed to read session data: user (path: D:\phpstudy_pro\Extensions\tmp\tmp) in D:\phpstudy_pro\WWW\cheshi\0606.php on line 52

要在read方法中return $value; 改成return serialize($value);

也可以这样写 return (string)$value;

第二次访问时,错误SQL语句是insert into sess values ('ntf7qg00e8lp8sqvlbuqgflcge','s:32:"s:26:"s:20:"s:14:"stu|s:3:"stu";',unix_timestamp())

数据库已经存在这个sess_id 主键的时候。要更改SQL插入语句

  $sql="insert into sess values ('$sess_id','$sess_value',unix_timestamp()) on duplicate key update sess_value='$sess_value',sess_time=unix_timestamp()";

实现代码:

需要引入mypdo库
class Session{
	private $mypdo;

	public function __construct(){
		session_set_save_handler(
             [$this,'open'],
             [$this,'close'],
             [$this,'read'],
             [$this,'write'],
             [$this,'destroy'],
             [$this,'gc']
		);
		session_start();
	}
	function open(){
		$this->mypdo=MyPDO::getInstance($GLOBALS['config']['database']);
	    return true;
	}
	//关闭会话
	function close(){
	    return true;
	}
	//读取会话
	function read($sess_id){
	      $sql="select sess_value from sess where sess_id='$sess_id'";
	      return (string)$this->mypdo->fetchColumn($sql);
	}
	//写入会话
	function write($sess_id,$sess_value){
	      $sql="insert into sess values ('$sess_id','$sess_value',unix_timestamp()) on duplicate key update sess_value='$sess_value',sess_time=unix_timestamp()";
	       return $this->mypdo->exec($sql)!==false;
	}
	//销毁会话
	function destroy($sess_id){
		$sql="delete from sess where sess_id='$sess_id'";
	     $this->mypdo->exec($sql);
	     return $this->mypdo->exec($sql)!==false;
	}
	//垃圾回收
	function gc($lifetime){
	     $expires=time()-$lifetime;
	     $sql="delete * from sess where sess_time<$expires";
	     $this->mypdo->exec($sql);
	     return $this->mypdo->exec($sql)!==false;
	}
}

new Session();
$_SESSION['stu']=['tom','berry','ketty'];
$_SESSION['name']="李白";
echo $_SESSION['name'];
print_r($_SESSION['stu']);
session_destroy();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值