2016-10-21 33 views
-1

當表單提交以下錯誤:PHP公告:未定義的偏移和索引

PHP Notice: Undefined offset: 1 in E:\php\learning2\increase.php on line 10

PHP Notice: Undefined index: quantity in E:\php\learning2\increase.php on line 10

形式:

<form action="increase.php" method="post"> 
    <input type="hidden" name="productId" value="1"> 
    <input type="number" name="productQuantity" value="1"> 
    <input type="submit" name="submit" value="Add to basket"> 
</form> 

increase.php

session_start(); 

if (isset($_POST['submit'])) { 
    $productId = $_REQUEST['productId']; 

    $productQuantity = $_REQUEST['productQuantity']; 

    $_SESSION['cart'][$productId]['quantity'] += $productQuantity; 

    header('Location: http://localhost:8000/'); 
} 

怎樣纔可以解決?

+0

號在session_start (); if(!isset($ _ SESSION ['cart'])){ $ _SESSION ['cart'] = []; } –

+0

我是一個被數字與字符串索引注意到的混淆:P –

回答

1

這些通知,其目的是爲了讓您瞭解爲什麼你的代碼可能不會在你希望的方式來運作:

$_SESSION['cart'][$productId]['quantity'] += $productQuantity; 

這裏:$productId(數字evaluted)不是一部分的數組$_SESSION['cart'],並且您正試圖像數組那樣對待它。 PHP會自動將它初始化爲一個數組,然後將該數組的['quantity']設置爲$productQuantity。因爲PHP正在做這個假設(因爲你試圖把它當作一個數組,它不會),它會拋出一個NOTICE異常。

你可以通過2種方式解決它。首先,你可以禁用通知,並假設這是工作的打算:

error_reporting(E_ALL & ~E_NOTICE); 

,或者通過顯式初始化數組(一個或多個)修復導致了它的錯誤:

if (!isset($_SESSION['cart'])) 
{ 
    $_SESSION['cart'] = array(); 
} 
if (!isset($_SESSION['cart'][$productId])) 
{ 
    $_SESSION['cart'][$productId] = array('quantity' => 0); 
} 
$_SESSION['cart'][$productId]['quantity'] += $productQuantity; 
+0

非常感謝您的詳細解答和幫助!我很感激。 –

+0

這個答案肯定會對你有幫助。 @RuTrashChannel。 *前進* –

+0

請不要建議禁止通知或警告。解決這些問題的唯一方法是糾正問題,而不是忽視它。在編寫新代碼時,總是使用'error_reporting = -1'(或者'error_reporting = E_ALL | E_STRICT',其中PHP 5.4不需要'E_STRICT') –