PHP使用$ _SESSION记住url参数值

时间:2014-11-19 11:44:34

标签: php session

我制作了一个脚本,显示" school_id "在url参数中。

http://mywebsite.com/mygrade?school_id=00000

我使用 $ _ GET [' school_id'] 来显示身份证号码。

<?php echo $_GET['school_id']; ?>

但我想要的是参数&#34; school_id &#34;为空,我想显示之前输入的数据。

例如,用户已经浏览了http://mywebsite.com/mygrade?school_id=00000,然后他浏览了 http://mywebsite.com/mygrade?school_id= 哪个ID没有值。它仍会显示 00000 ,这是他之前使用的ID。

我使用下面这段代码但不起作用.. :(

<?php
session_start(); 
$_SESSION['schoo_id'] = $_GET['school_id'];

if ($_GET['school_id'] === null || $_GET['school_id'] == ""){
    echo $_SESSION['schoo_id'];
}
else{
    $_GET['school_id'];
}
?>

任何得到我的观点并能帮助我的人?​​

5 个答案:

答案 0 :(得分:1)

我要逐行打破这个问题,如果我需要进一步解释,请在评论中告诉我:

自我解释:

<?php
session_start(); 

这里有一个错字:

$_SESSION['schoo_id'] = $_GET['school_id'];

但是!修复它无法解决您的问题。如果$_GET['school_id']未定义/空白,会发生什么?猜猜看,$_SESSION['school_id']现在是空白的。显然,您不希望出现此行为,因此如果$_SESSION['school_id']已定义

,您只需设置$_GET['school_id']

如果未定义,则访问$_GET['school_id']会抛出E_NOTICE错误,因此您需要检查其存在,而不是检查它是否为null

if ($_GET['school_id'] === null || $_GET['school_id'] == ""){

哦,这个错字是打算的。为什么拼错学校呢?没必要! :)

    echo $_SESSION['schoo_id'];

这是做什么的?没有!没有回音,没有。只是访问一个变量并且不做任何事情。

}
else{
    $_GET['school_id'];
}
?>

以下是您的代码应该是什么样的,或者至少我相信您的意图:

<?php
session_start();

if (isset($_GET['school_id']) && $_GET['school_id'] !== ""){
    $_SESSION['school_id'] = $_GET['school_id'];
}

// $_SESSION['school_id'] will be guaranteed to be what $_GET['school_id'] is (if set)
// or whatever it was last time it was defined
// always echo it.
echo $_SESSION['school_id'];
?>

答案 1 :(得分:0)

<?php
session_start(); 


if ($_GET['school_id'] === null || $_GET['school_id'] == ""){
    echo $_SESSION['schoo_id'];
}
else{
    $_GET['school_id'];
    $_SESSION['schoo_id'] = $_GET['school_id']; //here set the session
}
?>

答案 2 :(得分:0)

这里你需要做的是将GET值保存在SESSION中,只要它设置为以后使用,这样就可以了。

<?php
session_start(); 
if (!isset($_GET['school_id']) || $_GET['school_id'] === null || $_GET['school_id'] == ""){
    echo $_SESSION['schoo_id'];
}
else{
$_SESSION['schoo_id'] = $_GET['school_id'];
   echo  $_GET['school_id'];
}
?>

答案 3 :(得分:0)

你几乎拥有它。

<?php

session_start(); 


if (isset($_GET['school_id']) && trim($_GET['school_id']) !== '') {
    // its a fair assumption to make that 'school_id' is intended to be an integer,
    // however I will not make that assumption on the OP's behalf.
    $_SESSION['school_id'] = $_GET['school_id'];
}

if (isset($_SESSION['school_id']) {
    echo $_SESSION['school_id'];
}
else {
    echo 'have not entered a school id yet';
}
?>

答案 4 :(得分:0)

我同意 Salman A ,这是最简单的方法:

<?php
session_start(); 

if (is_int($_GET['school_id'])) $_SESSION['school_id'] = $_GET['school_id'];
// further use $_SESSION['school_id'] for your needs.

?>