Passing variables from a HTML form to PHP

One of the submissions in my form is Choose Your Opponent. It has 425 options based on a data query. The form element is a select list name = ‘opponent’. Here is the line that produces the the User sees.

while($opponent = mysqli_fetch_assoc($oresults)) {              
    echo '<option value = "'. $opponent['id'] .'">'. $opponent['school'] .'</option>';          

The user sees ‘school’, but it passes ‘id’ to the PHP. Is there a way to send both the value and what the option user sees to the PHP?

Only the opponent’s ‘id’ is going into the data table, but I want also send ‘school’ back to the user saying, "Your stats vs. ‘school’ has been submitted".

I know I can produce it with another query, but I’d rather not.

Stack Overflow Asked by Jim R on January 1, 2021

2 Answers

2 Answers

you can put both the id and the school in the option value as a string then convert it into an array

echo '<option value = "'. $opponent['id'] .','. $opponent['school'] .'">'. $opponent['school'] .'</option>';

you will probably receive a string of something like: 'id,school' next, convert this string into an array. refer to code below

$string = 'id,school'     // this is your select option value
$array = explode(',', $string)

above code will give you $array = [ 'id', 'school' ] which you can now output to your page.

echo 'Your stats '. $array[0] .' vs school '. $array[1] .' has been submitted';

Correct answer by BillJustin on January 1, 2021

You can send JSON with both or all data:

echo '<option value="'.htmlentities(json_encode($opponent)).'">'.$opponent['school'].'</option>';

Then in PHP:

$opponent = json_decode($_POST['opponent'], true);
echo $opponent['school'];

Answered by AbraCadaver on January 1, 2021

Add your own answers!

Related Questions

Why are declarations in a switch construct legal?

1  Asked on November 12, 2021 by l-s-roth


How do I import InvalidURL exception in praw for python?

1  Asked on November 12, 2021 by johannes-pertl


Place button on bottom of a div

7  Asked on November 12, 2021 by jackal


Javascript: using tuples as dictionary keys

4  Asked on November 12, 2021 by hasen


Gmail REST api batch support for getting messages

3  Asked on November 12, 2021 by dune76


Custom Route Doesn’t Get The Query String

2  Asked on November 12, 2021 by at-2017


Ask a Question

Get help from others!

© 2022 All rights reserved.