Robert Jones
Robert Jones

Reputation: 408

How to insert the value in a listbox from a database

I need some help with my code. I'm fetching the data from a database as I am storing the data in a $_SESSION array. Now I would like to insert the data in a listbox but I have got a problem with insert the data in a listbox.

When I try this:

<select id="gender" name="gender" class="form-control" value='<?php echo htmlspecialchars($_SESSION["gender"]); ?>'>
    <option value="unknown"></option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>

It will not insert the data in a listbox as the listbox show there is no data have been insert in a listbox.

Here is the full code:

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}
//print_r($_SESSION);
?>

<select id="gender" name="gender" class="form-control" value='<?php echo htmlspecialchars($_SESSION["gender"]); ?>'>
        <option value="unknown"></option>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
    </select>

Here is what the $_SESSION array show:

Array
(
    [loggedin] => 1
    [id] => 1
    [username] => myusername
    [firstname] => Robert
    [lastname] => Jones
    [email] => [email protected]
    [gender] => Male
    [states] => United Kingdom
)

Can you please show me an example how I can insert the data in a listbox using with php echo that I'm pulling the data from the $_SESSION array?

Thank you.

Upvotes: 0

Views: 473

Answers (1)

WKoppel
WKoppel

Reputation: 504

I would generate this select via PHP

$html = '<select id="gender" name="gender" class="form-control">';
$values = array('unknown', 'Male', 'Female');
foreach($values as $v){
    $selected = '';
    if($v == 'unknown'){
        $title = '';
    }else{
        $title = $v;
    }
    if($v == $_SESSION["gender"]){
        $selected = "selected";
    }
    $html .= "<option $selected value='$v'>$title</option>";
}
$html .= "</select>";
echo $html;

Upvotes: 2

Related Questions