简体   繁体   中英

How to not lose an array field text on PHP form?

I have an array input in a form. I want to validate the form using php and not loosing the input if any error occurs. I read previous questions and used the following codes:

<input type="text" name="name[]" value="<?php echo (isset($_POST['name']))?$_POST['name']:'';?>">
<input type="text" name="name[]" value="<?php echo (isset($_POST['name']))?$_POST['name']:'';?>">

As you see the input is an array.

The problem is when an error occurs, the inputs become Array not the previous text in the field. 在此处输入图片说明

How can I solve this problem?

When you used echo $_POST['name'] while $_POST['name'] is an array, you will echo "Array". You should echo each element in this array

<?php

if (is_array($_POST['name'])){
    foreach($_POST['name'] as $name){
        echo '<input type="text" name="name[]" value="' . htmlspecialchars($name) . '"\n"; 
    }
}

Also make it a habit to escape untrusted values with htmlspecialchars if you are going to inject them into the HTML, to protect against XSS attacks.

Since the input is an array, so is $_POST['name'] , so you need to index into it to get the name, using indexes in the same order as the inputs in your file :

<input type="text" name="name[]" value="<?php echo (isset($_POST['name'][0]))?$_POST['name'][0]:'';?>">
<input type="text" name="name[]" value="<?php echo (isset($_POST['name'][1]))?$_POST['name'][1]:'';?>">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM