How can I send Dynamic Dropdown Value and option name in PHP

Viewed 93

I'm trying to save a dynamic values (from api) to my localdb for offline processing. I have 2 fields, event_id and event_name in dropdown directly coming from the API.

<select name="event_id" class="form-control" id="change">
    <label>Select Live Event </label>
    <?php foreach($events as $event): ?>
        <option value="<?=$event->eventid;?>"> 
          <?=$event->name;?>
        </option>
    <?php endforeach; ?>
</select>

Now I want user to select an event and save both event id and event name in local database. I know how to handle event_id but problem is event_name.. How do I assign a variable to this so that I could save both event_id and event_name at the same time.

1 Answers

If you cant get the values from the database and HAVE to get it from the form, you could separate the values by a delimiter (which you know for sure doesnt appear in either your ID nor the name), semicolon for example.

            <select name="event_id" class="form-control" id="change">
                <label>Select Live Event </label>
                <?php foreach($events as $event): ?>
                    <option value="<?=$event->eventid . ';' . $event->name;?>"> 
                          <?=$event->name;?>
                    </option>
                <?php endforeach; ?>
            </select>

You can then take this value in PHP and explode it there:

$split = explode(';', $_POST['event_id']);
$id = $split[0];
$name = $split[1];

Make sure to check $split first if it has 2 elements so you can proceed.


If you CAN select the value from the database too, go for that.

Related