更新時間:2018-10-26 來源:黑馬程序員技術社區(qū) 瀏覽量:
session入庫以及php高版本(7.2)下session入庫報錯的解決辦法
我們在php7.0下,實現(xiàn)session入庫,代碼如下:
<?php
//連接數(shù)據(jù)庫
function conn(){
$link=mysqli_connect('localhost','root','aa','php1',3306);
mysqli_set_charset($link,'utf8');
return true;
}
function open(){
return conn();
}
function close(){
return true;
}
function read($sess_id){
global $link;
$sql = "select sess_value from sess where sess_id='{$sess_id}'";
$res=mysqli_query($link,$sql);
if(mysqli_fetch_row($res)[0]){
return mysqli_fetch_row($res)[0];
}
return '';
}
function write($sess_id,$sess_value){
global $link;
$time=time();
$sql="insert into sess values('{$sess_id}','{$sess_value}','{$time}')
on duplicate key update sess_value='{$sess_value}',sess_time='{$time}'";
return mysqli_query($link,$sql);
}
function delete($sess_id){
global $link;
$sql="delete from sess where sess_id='{$sess_id}'";
return mysqli_query($link,$sql);
}
function gc($lifetime){
global $link;
$nowtime=time();
$time=$nowtime-$lifetime;
$sql="delete from sess where sess_time<'{$time}'";
return mysqli_query($link,$sql);
}
session_set_save_handler('open','close','read','write','delete','gc');
session_start();
$_SESSION['name']="北京";
運行一切正常,可是一旦切換到高版本,例如7.2下,就會報錯,Warning: session_start(): Failed to read session data: user (path: ) 或者是其他莫名的錯,解決辦法也很簡單,只需要在read方法里面的return mysqli_fetch_row($res)[0],在返回之前做一下強制類型轉換即可,即改成return (string)mysqli_fetch_row($res)[0];但是沒強制轉換之前也是字符串,為什么就不行呢?嘿嘿,你如果到傳智來,我就告訴你。
本文版權歸黑馬程序員PHP+H5全棧工程師培訓學院所有,歡迎轉載,轉載請注明作者出處。謝謝!