PHP 下拉多选

发布于 2024-11-01 19:55:44 字数 12099 浏览 0 评论 0原文

我是编码和 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>

I am new to the world of coding and PHP. Having picked up some of the basics, I have put a form together. I'm sure there are much efficient ways to code a page however seeing I have put something together with what I have learnt so far, I am having troubling getting past on select a multi-select dropdown after the user has posted the page i.e. to remember what the user selected. Here is my entire code.

<?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>

EDIT

Guys, I have updated my code to reflect some of the suggestions below. Let me know if the page is better coded. I have not included suggestions such as $start++ just because I am trying to understand what it means. I love to make coding as short as possible but seeing that I am just learning, best to get a good foundation.

<?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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

对不⑦ 2024-11-08 19:55:44

您可以使用 in_array 函数检查当前 $mediavalue 是否在所选 $media 的数组中 - 但您需要为带有媒体源的数组选择另一个名称,因为它会覆盖用户选择的 $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 => 'internet', 1 => '小册子', 2 => '小册子');可以只是 $mediaTypes = array('internet', 'pamphlet', 'brochure');
  2. 当性别未设置时,$_POST['gender'] 会导致通知“未定义索引:性别”。
  3. $start=$start+1 可以压缩为 $start++;
  4. 最好重用用户输入的变量,而不是直接访问 $_POST

You can use in_array function to check whether the current $mediavalue in the array of selected $media - but you need to select another name for array with media sources, because it overwrites the $media variable with user selection. For example:

 $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;
 }

There are a few recommended minor modifications to you code as well:

  1. you do not need to use numbers in array - it duplicates the default behavior, so $mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); can be just $mediaTypes = array('internet', 'pamphlet', 'brochure');
  2. when gender is not set, $_POST['gender'] causes notice "Undefined index: gender".
  3. $start=$start+1 can be compacted to $start++;
  4. it is better to reuse the variables with user inputs instead of accessing $_POST directly
黎歌 2024-11-08 19:55:44

试试这个:

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

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

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

    echo $mediaform;

}

Try this:

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

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

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

    echo $mediaform;

}
凝望流年 2024-11-08 19:55:44

根据下拉列表的表单输出,设置 $_SESSION['variable'] 执行以下操作:

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

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

based on form output of the dropdown, set a $_SESSION['variable'] the do something like:

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

you could even include other elseif statements based on different parameters. Then use else as an error handle.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文