Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

php - How to post two values in an option field?

I'd like to post two values in one drop down option and I'm not sure about the best way to approach it.

The drop down list pulls data in from an external service. This data is 'id' and 'name'.

When I select an option in the drop down and then press submit I want the 'id' and the 'name' to be posted.

My code looks like this:

<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
    <option value="<?php echo $name['id']);?>">
       <?php echo $name['name']);?>
    </option>               
<?php endforeach; ?>
</select>

I've tried putting in a hidden input field, but that then doesn't render out the drop down (instead it just creates a list).

I am using both the id and name elsewhere, so I don't want to have to post just the id and then have to get the name again, hence I want to post both of them at the same time.

Any recommendations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot post two values unless both of them appear in the value attribute. You can place both in, separated by a comma or hyphen and explode() them apart in PHP:

// Place both values into the value attribute, separated by "-"
<option value="<?php echo $name['id'] . "-" . $name['name']);?>">
   <?php echo $name['name']);?>
</option>      

Receiving them in PHP

// split the contents of $_POST['data'] on a hyphen, returning at most two items
list($data_id, $data_name) = explode("-", $_POST['data'], 2);

echo "id: $data_id, name: $data_name";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...