Ir_123
Ir_123

Reputation: 25

Is it possible to send an array in a POST, or assign multiple values in one input tag, and how?

I want to send more than one value in the POST but use only one type of input tag.

For example, is it possible to set the value of the option tag to both $data['username_id] and $data['name'] and send it via the POST

<select name="owner" id="owner">
    <option value="NULL" selected="selected"></option>
    <?php
    $sql = 'SELECT * FROM users'
         . ' ORDER BY name';

    $query = mysqli_query($connect,$sql) or die (mysqli_error($connect));

    while ($data = mysqli_fetch_array($query))
    {
        ?>
        <option value="<?php echo $data['user_id']; ?>"><?php echo $data['name']; ?></option>
        <?php
    }
    ?>
</select>

I can't seem to retrieve on the other end. I have tried:

<option value="<?php echo $data['user_id','name']; ?>"><?php echo $data['name']; ?></option>

But still no luck.

Any help would be useful.

Upvotes: 0

Views: 45

Answers (1)

Martin
Martin

Reputation: 22760

For example, is it possible to set the value of the option tag to both $data['username_id]' and $data['name'] and send it via the POST

Yes, this can be done, carefully.

Working with your example:

 <option value="<?php echo $data['user_id','name']; ?>"><?php echo $data['name']; ?></option>

Can be simply rewritten as:

<option value='<?php echo $data['user_id']."--".$data['name']."'>"
               .$data['name']; ?></option>

At the other end:

On the form receiver PHP page:

$parts = explode("--",$_POST['owner']);
/***
 * $parts[0] = user_id
 * $parts[1] = name
 ***/

BUT as you are grabbing the data from a database row anyway, this is fairly pointless, you might as well JUST transport the user ID and simply use it on the receiving end to grab the 'name' data value from the Database.

There is also potential issues if the splitter (--) appears more than once, so be carefully to choose a splitter that does not apper in either of the values you are trying to send.


Working Freehand:

 <input name="whatever[]" value="one">
 <input name="whatever[]" value="two">

The square bracket means that the data passed in $_POST will be an array of values.

As pointed out in comments by Kainaw you can also simply use the multiple selection to reach the same effect in your <select> input.

Upvotes: 2

Related Questions