简体   繁体   中英

PHP POST giving undefined index

I'm a newbie in PHP so please don't judge.

I have this problem with an undefined index . I think I know what is my issue. The first time I load my code, I don't have any values, so I should define what to do when there are no values selected.

I tried lot of combinations with isset , but can't fix it. Maybe I just don't know how exactly write it down. Can someone please guide me with tips particular for my case?

Here is my code: https://pastebin.com/kLAS4JRv .

<?php

if (($_POST ['klausimas1'] == 0)) {
  echo '';
} elseif (($_POST ['klausimas1'] == 1)) {
  echo '<div class="alert alert-success">Taip, tai yra Elnias</div>';
} elseif (($_POST ['klausimas1'] != 1)) {
  echo '<div class="alert alert-danger">Ne, tai yra Elnias</div>';
}
if(isset($_POST['klausimas1'])) {
    if ($_POST ['klausimas1'] == 0) {
        echo '';
    } elseif ($_POST ['klausimas1'] == 1) {
        echo '<div class="alert alert-success">Taip, tai yra Elnias</div>';
    } elseif ($_POST ['klausimas1'] != 1) {
        echo '<div class="alert alert-danger">Ne, tai yra Elnias</div>';
    }
}

To check if a post is set, you're looking for isset . Then you just need to slightly restructure you code to only check for conditions inside of the isset check:

if(isset($_POST['klausimas1'])) {
  if ($_POST['klausimas1'] == 1) {
    echo '<div class="alert alert-success">Taip, tai yra Elnias</div>';
  } elseif ($_POST['klausimas1'] != 1) {
    echo '<div class="alert alert-danger">Ne, tai yra Elnias</div>';
  }
}

Also note that $_POST cannot have a space between it and the variable that you are checking against. I've fixed this in the above example.

Hope this helps! :)

You just check $_POST ['klausimas1'] in your code, you should check all the elements of post your're going to used.

You can use this, and you can define the default value for them.

$klausimas1 = isset($_POST ['klausimas1']) ? $_POST ['klausimas1'] : '';
$klausimas2 = isset($_POST ['klausimas2']) ? $_POST ['klausimas2'] : '';
$klausimas3 = isset($_POST ['klausimas3']) ? $_POST ['klausimas3'] : '';

or

if (isset ( $_POST ['klausimas1'] ) && isset($_POST ['klausimas2']) && isset($_POST ['klausimas3'])) {
    $klausimas1 = $_POST ['klausimas1'];
    $klausimas2 = $_POST ['klausimas2'];
    $klausimas3 = $_POST ['klausimas3'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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