Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach php function inside HTML select options

Tags:

html

php

Im a newbie to this forum and have just started coding in php. Need some help. I have the following code

<?php error_reporting(-1);

require_once('/mysql/sql_connect.php');

$q = "SELECT pty.pty_profile_name AS profile FROM pty, users WHERE users.username = 'testaccount' ";
    $r = @mysqli_query ($dbc, $q);

    $results_array = array();
    while($row = mysqli_fetch_assoc($r)) {
        array_push($results_array, $row);
    echo "<pre>"; print_r($results_array); echo "</pre>"; }

?>

<p>
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>  
   <select name="pty_select" > 
   <?php foreach($results_array as $key => $value){ ?>
                    <option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option> 
    <?php } ?>
        </select>
    <input type="submit" name="Submit" />
</form>

<?php 

if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?> 

The output I get is correct, but it displays the key, eg, 0 or 1 or 2, based on what I select in the form. I need the value output. Eg 0 = Emerton, it outputs "0" instead of Emerton.

If I echo $value['profile'] instead of pty_select, I get the last result of the query all the time. Which in this example would be 2, which is Ambarvale as I believe it just chooses the last row output of the query.

I hope I've made sense. Thanks in advance.

like image 227
Daniel Garcia Avatar asked Oct 30 '25 07:10

Daniel Garcia


1 Answers

It will obviously echo the key, as you assigned the value of options as $key if you need the options in the $_POST['pty_select'] use this:

 <select name="pty_select" > 
<?php foreach($results_array as $key => $value){ ?>
                <option value="<?php echo $value['profile'];?>"><?php echo $value['profile'];     ?></option> 
<?php } ?>
    </select>
like image 188
abhij89 Avatar answered Nov 01 '25 21:11

abhij89