php - $_SESSION 似乎只保留最后一个值
问题描述
请在此处查看测试页面https://wintoweb.com/sandbox/question_3.php 我使用 $_SESSION 来存储数据库搜索的结果,但只有最后一个值存储在会话中。看起来后者在每次搜索时都被清空。
我之前在该服务器上使用过会话并且没有问题。我的代码可能有问题,但我无法弄清楚。session_start 在文件顶部调用。
<?php
if(isset($_GET['search'])){
} else if(isset($_GET['display_this'])){
$rets = getNames(); //The $rets will hold the value returned by your function getName().
if(!empty($rets)){
echo '</br><b>Your selections so far :</b></br></br>';
}
//But yet, only the last search is stored in the session (why?)
echo "Echo of session array : " . $_SESSION['author'] . "<br>";
}
function getNames(){
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected . ' -- ';
// This should add every $rets to the session array. Right?
$_SESSION['author'] = $rets;
//session_write_close();
}
}
return $rets;
}
?>
我希望会话保留来自后续搜索的所有信息,但只存储最后一个值。
解决方案
您每次都用新值覆盖您的 Session 数组。您需要附加到它,就像附加到$rets
变量一样。
$_SESSION['author'] .= $rets;
推荐阅读
- time-complexity - 递归的时间复杂度
- python - Python模块没有属性而属性存在
- html - Flexbox 根据内容(问题)自动确定容器的大小(宽度)
- php - 检查变量中是否存在子字符串
- pyspark - 以编程方式定义 SQL 列的大小
- vuejs2 - 使用 VueJS 访问和使用 Firestore 子集合数据(菜鸟问题)
- qt - 使用 QGraphicsView 时,是否有一种“简单的方法”可以将自定义 UI 添加到 Qt 应用程序?
- java - JavaFX 应用程序设计
- rest - 有没有可以像 Telnet 一样使用的 REST api
- oracle - Oracle - 将行转换为列