問題描述
我正在用 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 錯誤:注意:未定義索引:的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!