2016-10-21 3 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/'); 
} 

는 어떻게 해결 될 수있다 ? 여기

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

:

+0

번호으로 session_start : 명시 적으로 배열 (들)을 초기화하여, 그것을 일으키는 오류를 수정,

error_reporting(E_ALL & ~E_NOTICE); 

또는 첫째, 당신은 통지를하지 않도록 의도 한대로이 작동하고 가정 할 수있다(); if (! isset ($ _ SESSION [ 'cart'])) { $ _SESSION [ 'cart'] = []; } –

+0

저는 숫자 대 문자열 색인 알림에 의해 캐치가 되살아납니다. P –

답변

1

이 당신이 의도 한 방식으로 작동하지 않을 코드에있는 이유에 당신에게 통찰력을 제공하도록 설계 사항이다 $productId는 (숫자는대로 계산) 일부가 아닌 배열 $_SESSION['cart']의 배열이고 배열처럼 취급하려고합니다. PHP는이를 자동으로 배열로 초기화 한 다음 해당 배열의 ['quantity']$productQuantity으로 설정합니다. PHP는이 가정을하고 있기 때문에 (배열로 취급하려고하고 있기 때문에), 예외주의를 던질 것입니다.

두 가지 방법으로 해결할 수 있습니다.

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. * Go ahead * –

+0

알림이나 경고를 표시하지 마십시오. 문제를 해결하는 ** ** 올바른 방법은 문제를 무시하고 무시하는 것이 아닙니다. 새로운 코드를 작성할 때는 항상'error_reporting = -1' (또는 PHP 5.4 이상에서는'E_STRICT'가 필요없는'error_reporting = E_ALL | E_STRICT')을 사용하십시오. –