Skip to content Skip to sidebar Skip to footer

Foreach Php Function Inside Html Select Options

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

Solution 1:

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:

<selectname="pty_select" ><?phpforeach($results_arrayas$key => $value){ ?><optionvalue="<?phpecho$value['profile'];?>"><?phpecho$value['profile'];     ?></option><?php } ?></select>

Solution 2:

You mean you need the value what you have used to display it. Then, Change to :

<optionvalue="<?phpecho$value['profile']; ?>"><?phpecho$value['profile']; ?></option>

Solution 3:

And now let's go to ideal world :)

Build data pairs database_id => name for options:

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

$values = array();
while($r = mysqli_fetch_row($r)) {
    $values[$r[0]] = $r[1];
}

Never use @ when working with database, why do you want to suppress errors instead of preventing/handling them?

Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:

functionselectbox($values = array(), $attributes = array(), $selected_value = null)
{
    // Headerecho'<select';
    foreach( $attributesas$key => $val){
        echo' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
    }
    echo'>';

    // Valuesforeach( $valuesas$key => $val){
        echo'<option value="' . htmlspecialchars( $key) .'"';
        if( $key === $selected_value){
            echo' selected="selected"';
        }
        echo'>' . htmlspecialchars( $val) . '</option>';
    }
    echo'</select>';
}

And now usage :)

<formmethod="post"action="foreach2.php"><labelfor="Property Select"class="title">Select Property</label><?php selectbox( $values, array( 'name' => 'pty_select')); ?><inputtype="submit"name="Submit" /></form>

And what to do with it then?

$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
    $name = $values[$id];
}

Solution 4:

Give

<optionvalue="<?phpecho$value['profile']; ?>"><?phpecho$value['profile']; ?></option>

instead of

<optionvalue="<?phpecho$key; ?>"><?phpecho$value['profile']; ?></option>

Solution 5:

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

Change it to something like

if(isset($_POST['Submit'])) {
    echo$results_array[$_POST['pty_select']]['profile'];
}

Or alternatively use profile option value.

Post a Comment for "Foreach Php Function Inside Html Select Options"