下拉列表保持选中的最后一个值输入php

时间:2013-02-28 17:00:40

标签: php drop-down-menu

我在php中创建了一个用户个人资料页面。用户插入性别和电话号码,所有这些都存储在名为profile的表中的数据库中。我的问题是如何使下拉列表保持用户以前输入的选定值。例如,如果用户选择Male,则下拉列表应将Male保留为选定选项,并且仅在用户决定再次更改时才更改。

以下是代码:

<form   action=""   method="POST"  >      
<?php

if ( isset($_GET['success']) === true && empty($_GET['success'])===true ){
    echo'Profile Updated Sucessfuly';
}else{
    if( empty($_POST) === false  &&  empty($errors) === true ){
        $update_data_profile = array('gender' => $_POST['gender'],
                                                 'telephone' => $_POST['telephone']);

        update_user_profile($session_user_id, $update_data_profile);
        header('Location: profile_update.php?success');                             
        exit();
    }else if ( empty($errors) === false ){
        echo output_errors($errors);
    }
?>


Gender<select name="gender"  id="gender"> 
    <option value=" "> EMPTY </option> 
    <option value="Male">Male</option> 
    <option value="Female">Female</option> 
</select>

Telephone <input name="telephone" type="text" size="25" />

<input type="submit" value="" name="submit"/></br>

这是我用来在数据库中插入数据的函数:

function update_user_profile($user_id, $update_data_profile){

   $result = mysql_query("select user_id from profile where user_id = $user_id limit 1");

     $user_id = $update_data_profile['user_id'] ;

    if(count($update_data_profile)){

    $columns = array();
    $values = array();

    foreach($update_data_profile as $field => $data){
    $columns[] = $field;
    $values[] = $data;
    } 
    }

mysql_query(" INSERT INTO `profile` (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')" ) or die (mysql_error());

3 个答案:

答案 0 :(得分:0)

从此您将获得逻辑

<select name="gender" id="gender">
<?php
  if($_POST['gender'] == 'male' {
    echo '<option value="Male" selected>Male</option>';
  } else {
    echo '<option value="Female" selected>Female</option>';
?> 
</select>

答案 1 :(得分:0)

您可以在页面加载期间检索最后一个Gender并添加所选选项。

<?php
    result = mysql_fetch_array(mysql_query("SELECT user_id FROM profile ORDER BY user_id DESC LIMIT 1"));
    $gender = $result['gender'];  //you need to change the ['gender'] with what your column name is for gender.
?>
<select name="gender"  id="gender"> 
    <option value=" "> EMPTY </option> 
    <option value="Male" <?php if($gender == "Male") echo "selected='selected'"; ?>>Male</option> 
    <option value="Female" <?php if($gender == "Female") echo "selected='selected'"; ?>>Female</option> 
</select>

答案 2 :(得分:-1)

您可以像这样更改代码:

<select name="gender"  id="gender" default="Male">