繁体   English   中英

没有数据发送时如何处理GET变量

[英]How can I handle a GET variable when there is no data being sent

在我的网页上,我有2个选项,用于创建新列表或编辑现有列表。

如果用户希望创建一个新列表,则会出现一个带有文本区域的新页面。

如果用户希望编辑现有列表,则显示列表,然后用户可以选择一个列表。 选择列表后,用户将被重定向到新列表页面,其中的文本区域内容已被填充。

我在新列表页面中有以下if语句,可以接受来自编辑列表页面的输入:

$items = $_GET['items'];
if ($items){
    //get the stuff from the db and populate the text area
}
else {
    //a new empty text area
}

问题是,当我尝试直接从“创建新列表”选项访问此页面时,收到一条错误消息,指出items是未定义的变量。 这是有道理的,因为原始页面没有发送任何数据,因此没有任何内容。

我该如何解决? 我可以将原始页面设置为发送items的空值,但我想避免更改原始页面。 是否有一个选项可以检查请求的来源,或者是否只有在可以接收到变量的情况下才激活变量(可由GET功能使用)?

使用isset()

isset —确定是否设置了变量并且不为NULL

if (isset($_GET['items'])){
    //get the stuff from the db and populate the text area
    $items = $_GET['items'];
}

@Eugen建议(在分配变量之前检查:

$items = isset($_GET['items']) ? $_GET['items'] : null; 
if($items) { // bla bla }

首先,您必须写/检查

print_r($_GET)

如果只想检查一下就可以使用

if(isset($_GET["items"]){
      //it have a value
}

加:如果已使用unset()取消设置了变量,则将不再设置该变量。 如果测试已设置为NULL的变量,则isset()将返回FALSE。 另请注意,NULL字节(“ \\ 0”)不等于PHP NULL常量。

你要这个。 您需要检查是否设置了$_GET['items'] ,然后可以将$items设置$items结果。

if (isset($_GET['items']) && $items = $_GET['items']){
    //get the stuff from the db and populate the text area
}
else {
    //a new empty text area
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM