TransWikia.com

Passing variables from a HTML form to PHP

Stack Overflow Asked by Jim R on January 1, 2021

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.

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!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP