PHP下拉多选

时间:2011-04-17 01:51:46

标签: php drop-down-menu

我是编码和PHP的新手。在掌握了一些基础知识后,我将表格放在了一起。我确信有很多有效的方法可以对页面进行编码,但是看到我已将所学内容与迄今为止所学到的内容放在一起,我在用户发布页面后选择多选下拉列表时遇到了麻烦记住用户选择的内容。这是我的整个代码。

<?php
//Process form variables

//Validate if the form has been submitted
if(isset($_POST['submit'])) {

    //Validate if the form elements were completed
    $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
    $lname = isset($_POST['lname']) ? $_POST['lname'] : '';
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $gender = isset($_POST['gender']) ? $_POST['gender'] : '';
    $updates = isset($_POST['updates']) ? $_POST['updates'] : '';
    $media = isset($_POST['media']) ? $_POST['media'] : '';
    $comments = isset($_POST['comments']) ? $_POST['comments'] : '';

    //Place error messages in an array
    $errormsg = array();

    if(empty($fname)) {
            $errormsg[0] = 'Please specify your first name. It\'s blank.';
        }

    if(empty($lname)) {
            $errormsg[1] = 'Please specify your last name. It\'s blank.';
        }

    if(empty($email)) {
            $errormsg[2] = 'Please provide an email address. It\'s blank.';
    }

    if(empty($gender)) {
        $errormsg[3] = 'Please select a gender. It\'s blank.';
    }

    if(empty($updates)) {
        $errormsg[4] = 'Please select how we can contact you. It\'s blank.';
    }

    if(empty($media)) {
        $errormsg[5] = 'Please select where you heard about us. It\'s blank.';  
    }

    if(empty($comments)) {
        $errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
    }

    //Return list of error messages
    foreach($errormsg as $errormsg) {
        echo $errormsg .  '<br />';
    }

    //Debug
    print_r($_POST['media']);
}

?>
<html>
    <head>
        <title>Sample Registration Form</title>
    </head>

    <body>
        <h2>Sample Registration Form</h2>

            <form name="registration" method="post" action="registration.php">
                <div>
                    First Name:  <br />
                    <input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
                </div>

                <div>
                    Last Name: <br />
                    <input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
                </div>

                <div>
                    Email Address: <br />
                    <input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
                </div>

                <div>
                    Gender: <br />
                    <?php
                    //Generate gender array
                    $gender = array('male', 'female');
                    $countgender = count($gender);

                    for($start=0;$start < $countgender;$start=$start+1) {

                        $status = '';

                        if(isset($_POST['submit'])) {
                            if($_POST['gender'][0] == $gender[$start]) {
                                $status = 'checked';
                                // echo $gender[$start];
                            }
                        }

                        $genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
                        echo $genderform;

                    }                       

                        // foreach($gender as $gender) {

                            // $status = '';

                            // if(isset($_POST['submit'])) {

                                // if($_POST['gender'][0] == $gender) {
                                    // $status = 'checked';
                                // }
                            // }

                            // $genderform = '<input type="radio" name="gender[]" value="' .$gender . '" ' . $status .'>'. $gender . '';
                            // echo $genderform;
                        // }
                    ?>
                </div>

                <div>
                    Would you like to receive updates from us? <br />
                    <?php
                    $updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');

                    foreach($updates as $updatekeys => $updatevalues) {

                        $status = '';

                        if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
                            $status = 'checked';
                            // echo $_POST['updates'][$updatevalues];

                        }

                        echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
                    }

                    ?>
                </div>

                <div>
                    How did you hear about us? <br />

                    <select name="media[]" multiple>
                    <?php

                        $media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');

                        foreach($media as $mediakey => $mediavalue) {

                            $mediaform = '<option value="'. $mediavalue . '">'.$mediavalue.'</option>';
                            echo $mediaform;

                        }
                    ?>
                    </select>
                </div>

                <div>
                    Tell us what you think: <br />
                    <textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
                </div>

                <div>
                    <input type="submit" name="submit" value="submit">
                </div>
            </form>
    </body>
</html>

修改

伙计们,我已经更新了我的代码,以反映下面的一些建议。如果页面编码更好,请告诉我。我没有包括诸如$ start ++之类的建议,因为我试图理解它的含义。我喜欢让编码尽可能短,但看到我只是在学习,最好能够获得良好的基础。

<?php
//Initialize session
session_start();

//Generate session id
echo session_id() . '<br />';

//Process form variables

//Validate if the form has been submitted
if(isset($_POST['submit'])) {

    //Validate if the form elements were completed
    $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
    $lname = isset($_POST['lname']) ? $_POST['lname'] : '';
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $gender = isset($_POST['gender']) ? $_POST['gender'] : '';
    $updates = isset($_POST['updates']) ? $_POST['updates'] : '';
    $media = isset($_POST['media']) ? $_POST['media'] : '';
    $comments = isset($_POST['comments']) ? $_POST['comments'] : '';

    //Place error messages in an array
    $errormsg = array();

    if(empty($fname)) {
            $errormsg[0] = 'Please specify your first name. It\'s blank.';
        }

    if(empty($lname)) {
            $errormsg[1] = 'Please specify your last name. It\'s blank.';
        }

    if(empty($email)) {
            $errormsg[2] = 'Please provide an email address. It\'s blank.';
    }

    if(empty($gender)) {
        $errormsg[3] = 'Please select a gender. It\'s blank.';
    }

    if(empty($updates)) {
        $errormsg[4] = 'Please select how we can contact you. It\'s blank.';
    }

    if(empty($media)) {
        $errormsg[5] = 'Please select where you heard about us. It\'s blank.';  
    }

    if(empty($comments)) {
        $errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
    }

    //Return list of error messages
    foreach($errormsg as $errormsg) {
        echo $errormsg .  '<br />';
    }

    //Debug
    // print_r($_POST['media']);
}

?>
<html>
    <head>
        <title>Sample Registration Form</title>
    </head>

    <body>
        <h2>Sample Registration Form</h2>

            <form name="registration" method="post" action="registration.php">
                <div>
                    First Name:  <br />
                    <input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
                </div>

                <div>
                    Last Name: <br />
                    <input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
                </div>

                <div>
                    Email Address: <br />
                    <input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
                </div>

                <div>
                    Gender: <br />
                    <?php
                    //Generate gender array
                    $gender = array('male', 'female');
                    $countgender = count($gender);

                    for($start=0;$start < $countgender;$start=$start+1) {

                        $status = '';

                        if(isset($_POST['submit']) && !empty($_POST['gender'])) {
                            $status = in_array($gender[$start], $_POST['gender']) ? 'checked' : '';
                        }

                        $genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
                        echo $genderform;

                    }                       

                    ?>
                </div>

                <div>
                    Would you like to receive updates from us? <br />
                    <?php
                    $updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');

                    foreach($updates as $updatekeys => $updatevalues) {

                        $status = '';

                        if(isset($_POST['submit']) && !empty($_POST['updates'])) {
                            $status = in_array($updatevalues, $_POST['updates']) ? 'checked' : '';
                        }

                        // if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
                            // $status = 'checked';
                            // echo $_POST['updates'][$updatevalues];

                        // }

                        echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
                    }

                    ?>
                </div>

                <div>
                    How did you hear about us? <br />

                    <select name="media[]" multiple>
                    <?php

                        $media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');

                        foreach($media as $mediakey => $mediavalue) {

                            $status = in_array($mediavalue,$_POST['media'])? 'selected' : '';

                            $mediaform = '<option value="'. $mediavalue . '" '. $status .'>'.$mediavalue.'</option>';
                            echo $mediaform;

                        }
                    ?>
                    </select>
                </div>

                <div>
                    Tell us what you think: <br />
                    <textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
                </div>

                <div>
                    <input type="submit" name="submit" value="submit">
                </div>
            </form>
    </body>
</html>

3 个答案:

答案 0 :(得分:2)

您可以使用in_array函数来检查所选$ media数组中的当前$ mediavalue是否 - 但您需要为具有媒体源的数组选择另一个名称,因为它会覆盖带有用户选择的$ media变量。例如:

 $mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
 foreach($mediaTypes as $mediakey => $mediavalue) {
   $mediaform = '<option value="'. $mediavalue . '" '
     . (in_array($mediavalue, $media) ? 'selected' : '') . '>' . $mediavalue.'</option>';
   echo $mediaform;
 }

对您的代码也有一些建议的小修改:

  1. 您不需要在数组中使用数字 - 它会复制默认行为,因此$ mediaTypes = array(0 =&gt;'internet',1 =&gt;'pamphlet',2 =&gt;'brochure');可以只是$ mediaTypes = array('internet','pamphlet','brochure');
  2. 未设置性别时,$ _POST ['gender']会导致通知“未定义索引:性别”。
  3. $ start = $ start + 1可以压缩为$ start ++;
  4. 最好使用用户输入重用变量,而不是直接访问$ _POST

答案 1 :(得分:1)

试试这个:

foreach($media as $mediakey => $mediavalue) {

    $selected=in_array($mediavalue,$_POST['media'])?"selected":"";

    $mediaform = '<option '.$selected.' value="'. $mediavalue . '">'.$mediavalue.'</option>';

    echo $mediaform;

}

答案 2 :(得分:0)

根据下拉列表的表单输出,设置$ _SESSION ['variable']做类似的事情:

if (isset($_SESSION['variable'])) {
// if exists
}
else {
// if doesn't exist
}

你甚至可以根据不同的参数包含其他elseif语句。然后使用else作为错误句柄。