简体   繁体   English

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

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

On my webpage, I have 2 options, to create a new list or to edit an existing list. 在我的网页上,我有2个选项,用于创建新列表或编辑现有列表。

If the user wishes to create a new list, a new page with a textarea comes up. 如果用户希望创建一个新列表,则会出现一个带有文本区域的新页面。

If the user wishes to edit an existing list, the lists are displayed and the user can select a list. 如果用户希望编辑现有列表,则显示列表,然后用户可以选择一个列表。 Upon selection of the list, the user is redirected to the new list page with the text area contents already filled in. 选择列表后,用户将被重定向到新列表页面,其中的文本区域内容已被填充。

I have this if statement in the new list page to accept input from the edit-list page: 我在新列表页面中有以下if语句,可以接受来自编辑列表页面的输入:

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

The issue is that when I try reaching this page directly from the 'create new list' option, I get an error stating that items is an undefined variable. 问题是,当我尝试直接从“创建新列表”选项访问此页面时,收到一条错误消息,指出items是未定义的变量。 This makes sense as the original page is not sending any data so there is nothing to get. 这是有道理的,因为原始页面没有发送任何数据,因此没有任何内容。

How can I work around this? 我该如何解决? I can set the original page up to send a null value for items but I want to refrain from changing the original page. 我可以将原始页面设置为发送items的空值,但我想避免更改原始页面。 Is there an option to check from where the request is coming from, or an option to activate a variable only if it can be received (usable by the GET feature)? 是否有一个选项可以检查请求的来源,或者是否只有在可以接收到变量的情况下才激活变量(可由GET功能使用)?

Use isset() : 使用isset()

isset — Determine if a variable is set and is not NULL isset —确定是否设置了变量并且不为NULL

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

@Eugen suggestion(check before assigning the variable: @Eugen建议(在分配变量之前检查:

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

Firstly you must write/check 首先,您必须写/检查

print_r($_GET)

if you want only check it you can use 如果只想检查一下就可以使用

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

Plus:If a variable has been unset with unset(), it will no longer be set. 加:如果已使用unset()取消设置了变量,则将不再设置该变量。 isset() will return FALSE if testing a variable that has been set to NULL. 如果测试已设置为NULL的变量,则isset()将返回FALSE。 Also note that a NULL byte ("\\0") is not equivalent to the PHP NULL constant. 另请注意,NULL字节(“ \\ 0”)不等于PHP NULL常量。

You want this. 你要这个。 You need to check if $_GET['items'] is set, and then you can set $items to the result. 您需要检查是否设置了$_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