dongxingchang9345 2016-05-11 11:32 采纳率: 0%
浏览 31
已采纳

PHP会话数组和输入验证

Currently I am sending error messages and storing the value of my input fields in sessions.

Form example

<label class="errormsg"><?php echo $_SESSION['msgProductPrice']; unset($_SESSION['msgProductPrice']); ?></label>

<input type="text" name="product_price" value="<?php echo $_SESSION['val_ProductPrice']; unset($_SESSION['val_ProductPrice']); ?>" />

PHP

$Price = $_POST['product_price'];
$errorcount = 0;

if(empty($Price) === true){
    $PriceErrormsg = "empty";
    $errorcount++;
}

if($errorcount === 0) {
   // success
} else {
   $_SESSION['val_ProductPrice'] = $Price;
   $_SESSION['msgProductPrice'] = $PriceErrormsg;
}

This works perfectly with one of a kind input field. If I try with multiple input fields with the same name, it doesn't work.

Form example

<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />

<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />

This is where I'm unsure on how to validate all the input fields, how to keep the value in each input field when you hit submit and how to send an errormsg about each field?

PHP

$Amount= $_POST['product_amount'];
$errorcount = 0;

if(empty($Amount) === true){
    $AmountErrormsg = "empty";
    $errorcount++;
}

if($errorcount === 0) {
   // success
} else {
   $_SESSION['val_ProductAmount'] = $Amount;
   $_SESSION['msgProductAmount'] = $AmountErrormsg;
}
  • 写回答

2条回答 默认 最新

  • dspym82000 2016-05-11 11:57
    关注

    If I understand your problem, multiple product amounts are being submitted, and you want to validate each one individually and display the error message next to the appropriate textbox?

    Because you are receiving an array of values, you need to create a corresponding array of error messages.

    It's a while since I've done any PHP, so this might not be 100% correct, but I think you need something along these lines...

    $AmountErrorMessage = Array();
    foreach ($Amount as $key => $value) {
        if (empty($value)) {
            $AmountErrorMessage[$key] = 'empty';
        }
    }
    
    if ($AmountErrorMessage->count() > 0) {
        // success
    } else {
        $_SESSION['val_ProductAmount'] = $Amount;
        $_SESSION['msgProductAmount'] = $AmountErrorMessage;
    }
    

    You would then also need to iterate through the array in order to generate the HTML for your form, creating a label and input box for each value submitted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?