沃梦达 / 编程问答 / php问题 / 正文

PHP 错误:注意:未定义索引:

PHP error: Notice: Undefined index:(PHP 错误:注意:未定义索引:)

本文介绍了PHP 错误:注意:未定义索引:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 PHP 处理购物车,但似乎在各种地方都收到此错误注意:未定义索引:".错误是指不同地方编码的相似位.例如,我有一段代码可以计算用户决定订阅的月份的套餐价格.我有以下错误所指的变量:

I am working on a shopping cart in PHP and I seem to be getting this error "Notice: Undefined index:" in all sorts of places. The error refers to the similar bit of coding in different places. For example I have a piece of coding that calculates a package price with the months a user decides to subscribe. I have the following variables where the errors refers to:

    $month = $_POST['month'];
    $op = $_POST['op'];

$month 变量是用户在表单中输入的数字,$op 变量是不同的包,其值存储在用户从表单上的单选按钮中选择的变量中.

The $month variable is the number the user inputs in a form, and the $op variable is different packages whose value are stored in a vriable that a user selects from radio buttons on the form.

我希望这在某种程度上是清楚的.

I hope that is clear in some way.

谢谢

抱歉忘了提到当用户提交数据时它们会消失.但是当他们第一次来到页面时,它会显示这个错误.我怎样才能摆脱它而不显示它?

Sorry forgot to mention that they do go away when the user submits the data. But when they first come to the page it displays this error. How I can get rid of it so it doesnt display it?

--

这是代码:

<?php
    $pack_1 = 3;
    $pack_2 = 6;
    $pack_3 = 9;
    $pack_4 = 12;
    $month = $_POST['month'];
    $op = $_POST['op'];
    $action = $_GET['action'];

    if ( $op == "Adopter" ) {
       $answer = $pack_1 * $month;
    }

    if ( $op == "Defender" ) {
      $answer = $pack_2 * $month;
    }

    if ( $op == "Protector" ) {
      $answer = $pack_3 * $month;
    }

    if ( $op == "Guardian" ) {
      $answer = $pack_4 * $month;
    }

    switch($action) {   
        case "adds":
            $_SESSION['cart'][$answer][$op];
            break;
    }
?>  

推荐答案

您正试图访问未设置的数组中的索引.这会引发通知.

You're attempting to access indicies within an array which are not set. This raises a notice.

很可能您现在已经注意到它,因为您的代码已移至 php.ini 将 error_reporting 设置为包含 E_NOTICE 的服务器.通过将 error_reporting 设置为 E_ALL & 来抑制通知~E_NOTICE(不推荐),或者在尝试访问之前验证索引是否存在:

Mostly likely you're noticing it now because your code has moved to a server where php.ini has error_reporting set to include E_NOTICE. Either suppress notices by setting error_reporting to E_ALL & ~E_NOTICE (not recommended), or verify that the index exists before you attempt to access it:

$month = array_key_exists('month', $_POST) ? $_POST['month'] : null;

这篇关于PHP 错误:注意:未定义索引:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP 错误:注意:未定义索引:

基础教程推荐