Erik Lassen
Erik Lassen

Reputation: 57

Posting php form with variable contents

I have the below code. It's a function creating a from containing a dropdown menu and a selectionbox, and is being called from a different page).

<?php
require_once 'forbindtilDB.php';

    function populerDropdownsOpretProgram()
    {
        global $mysqliOOP;
        $stmt = $mysqliOOP->prepare("SELECT DISTINCT primaer FROM oevelser ORDER BY primaer ASC");
       ?>
<form action="temp.php" method="post">
    <select multiple> 
    <option value="0">Vælg ønskede øvelse(r)</option>
        <?php
            $stmt->execute();
            $stmt->bind_result($primaereMuskelgruppe);
            while ($stmt->fetch())
            {
        ?>
            <option value = "<?php echo $primaereMuskelgruppe;?>" >
                <?php echo $primaereMuskelgruppe;
                ?>
            </option>
            <?php
            }  
            $stmt->close();
            ?>              
    </select>
    <?php 
    $stmt = $mysqliOOP->prepare("SELECT antalreps FROM antalreps ORDER BY antalreps ASC");
    ?>
    <select> 
    <option value="0">Vælg ønskede antal gentagelser</option>
        <?php
            $stmt->execute();
            $stmt->bind_result($antalreps);
            while ($stmt->fetch())
            {
        ?>
            <option value = "<?php echo $antalreps;?>" >
                <?php echo $antalreps;
                ?>
            </option>
            <?php
            }  
            $stmt->close();
        ?>      
    </select>
    <input type="submit">
    </form>
<?php       
}

I want to post the user input on a different page (currently temp.php), but I don't know how to handle the fact that the form contents is variables fetched by a mysqli call.

So far I've tried different versions of the below on the temp.php-page

<?php
        echo $_POST[$antalreps];
    ?>
    <?php
        echo $_POST[$primaereMuskelgruppe];
    ?>

But I'm getting errors stating that there is undefined variables (antalreps and primaeremuskelgruppe) and undefined indexes...

Also, there's the added complexity that the selection box may return more than one result.

Pretty sure echo $_POST[$antalreps]; etc. is the wrong way to go about this, but I haven't been able to figure out alternatives...

Any hints?

Upvotes: 0

Views: 58

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

You should add 'name' to your select and then use it.

For example instead of:

<select> 

you should have:

<select name="yourname">

and then in php to display its value use:

echo $_POST['yourname'];

and for select multiple you can use:

<select name="othername[]">

and then in PHP use it as array:

foreach ($_POST['othername'] as $item) {
   echo $item;
}

of course where I put yourname and othername you should put descriptive name such as colours for color box and similar

Upvotes: 1

Related Questions