【问题标题】:Multiple option and keeping selected value多个选项并保持选定的值
【发布时间】:2017-04-19 18:45:23
【问题描述】:

我有一个表单,其中包含一个多选框,其中填充了从数据库表中提取的治疗师姓名。

这是我的代码:

<div class="form-group col-sm-6 col-md-4">
    <label for="therapist"><strong>Senior Practitional / SP: </strong></label>                                                
    <select name="therapist[]" id="therapist" multiple="multiple" class="form-control selectpicker" multiple data-live-search="true" data-live-search-placeholder="Search" data-actions-box="true" data-parsley-trigger="change" required-no>
        <?php
        require_once('include/database.php');

        // read current record's data
        try {
            // prepare select query
            $getUser = "select firstname, lastname, profession from user WHERE user_type = 'therapist'";
            $stmt    = $con->prepare($getUser);

            // execute our query
            $stmt->execute();

            // store retrieved row to a variable
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

                // values to fill up our form
                $firstname  = $row['firstname'];
                $lastname   = $row['lastname'];
                $profession = $row['profession'];

                echo '<option id="firstname_' . $row['id'] . '" value="' . $row['id'] . '">' . $row['firstname'] . ' ' . $row['lastname'] . ' - ' . $row['profession'] . '</option> ';
            }
        }

        // show error
        catch (PDOException $exception) {
            die('ERROR: ' . $exception->getMessage());
        }
        ?>
    </select>                                           
</div> 

但我面临的问题是,如果我选择多个治疗师,我只能在结果表中得到一个整数 1

** 第二期 **

我遇到的另一个问题是,我有一个time_of_visit 表单字段,它是一个多选:

<?php $time_of_visit = $time_of_visit; ?>                       
<div class="form-group col-md-4">
    <label for="tov"><strong>Time of Visit: </strong></label>
    <select name="tov[]" class="form-control selectpicker" value='<?php echo $time_of_visit; ?>' multiple
        data-live-search="true" data-live-search-placeholder="Search" data-actions-box="true" data-parsley-trigger="change" required-no>
        <!-- <option selected>Select Visit Time...</option> -->
        <option name="tov[]" <?php if (isset($time_of_visit) && $time_of_visit == "am") echo "selected"; ?> value="am" selected>Am</option>
        <option name="tov[]" <?php if (isset($time_of_visit) && $time_of_visit == "lunch") echo "selected"; ?> value="lunch" selected>Lunch</option>
        <option name="tov[]" <?php if (isset($time_of_visit) && $time_of_visit == "pm") echo "selected"; ?> value="pm">Pm</option>
        <option name="tov[]" <?php if (isset($time_of_visit) && $time_of_visit == "am_pm") echo "selected"; ?> value="am_pm">Am or Pm</option>
        <option name="tov[]" <?php if (isset($time_of_visit) && $time_of_visit == "pm_care") echo "selected"; ?> value="pm_care">Pm Care</option>                                                                                                   
        <option name="tov[]" <?php if (isset($time_of_visit) && $time_of_visit == "single") echo "selected"; ?> value="5pm" selected>>5pm</option>
    </select>                                           
</div>

提交表单后,我收到time_of_visit cannot be null。我猜我可能在数据库中将其设置为Yes NULL,稍后我可以更改,但无论查询失败还是成功,我似乎都无法保留所选选项。

【问题讨论】:

  • 对于$row['id'] id 必须在SELECT
  • 嗯……这就是重点……让我试试看。
  • 我认为 u_mulder 得到了那个。还有一种更好的方法可以检测和设置选项:stackoverflow.com/questions/39070359/…stackoverflow.com/questions/18733545/…
  • @u_mulder...效果不佳...我的结果中有一个字符串Array...$getUser = "select id, firstname,...while ($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)){ $id = $row['id']; $firstname = $row['firstname'];
  • 在什么结果

标签: php html database validation mysqli


【解决方案1】:

我稍微清理了您的代码并重写了它,以便您可以测试提交表单时会发生什么。试试这个并确保表单输出您选择的正确 ID。

<?php
require_once('include/database.php');

// read current record's data
try {
    // prepare select query
    $getUser = "SELECT id, firstname, lastname, profession FROM user WHERE user_type = 'therapist'";
    $stmt    = $con->prepare($getUser);

    // execute our query
    $stmt->execute();
    // initialize options variable so that it doesn't get overwritten
    $options = "";
    // store retrieved row to a variable
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

        // values to fill up our form
        $firstname  = $row['firstname'];
        $lastname   = $row['lastname'];
        $profession = $row['profession'];
        /*use ".=" so that you add to the $options, rather than overwrite the last row*/
        $options .= '<option value=' . $row['id'] . '>' . $row['firstname'] . ' ' . $row['lastname'] . ' - ' . $row['profession'] . '</option>';
    }
}

// show error
catch (PDOException $exception) {
    die('ERROR: ' . $exception->getMessage());
}
// echo selections on form submit
    if(isset($_POST['submit'])) {
        foreach($_POST['therapist'] as $selection) {
            echo $selection . "\n";
        }
    ?>

    <div class="form-group col-sm-6 col-md-4">
        <form action="" method="POST">
            <label for="therapist"><strong>Senior Practitional / SP: </strong></label>                                                
            <select name="therapist[]" multiple>
                <?php echo $options; ?>
            </select>
            <input type="submit" name="submit" value="Submit"/>
        </form>
    </div> 

更新

问题的最终原因是您试图将数组插入到 sql 数据库中。您不能将数组直接插入到 sql 表中,因此必须在插入其值之前转换数组。请参阅下面的编辑。

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

// Use the implode() function to convert the array into a comma-delimited string
$therapists = implode(',', $_POST['therapist']);
// echo $therapists . "<br>"; // Uncomment this line to see how the imploded array looks
// Now you can include the therapists in your INSERT statement like so:
$sql = "INSERT INTO `table` (`column_name`) VALUES ('".$therapists."')";
}
?>

<div class="form-group col-sm-6 col-md-4">
    <form action="" method="POST">
        <label for="therapist"><strong>Senior Practitional / SP: </strong></label>                                                
        <select name="therapist[]" multiple>
            <?php echo $options; ?>
        </select>
        <input type="submit" name="submit" value="Submit"/>
    </form>
</div> 

在自己的列中显示每个治疗师

查询表格并返回存储在治疗师列中的值后,您可以使用 explode() 函数将字符串转换回数组,以便根据您的评论在新列中显示每个治疗师。

假设您将这些值存储在变量$therapists

$string_to_array = explode(",", $therapists);
// print_r($string_to_array); // Uncomment this line to see how the new array looks
// Should look like this: Array ( [0] => therapist1 [1] => therapist2 [2] => therapist3 [3] => therapist4 )

// Now loop through the array to display each name
$columns = ""; // Initialize $columns to avoid being overwritten
foreach ($string_to_array as $key => $value) {
    $columns .= "<td>$value</td>";
}
?>
<!--Echo $columns in table row-->
<table>
    <tr><?php echo $columns; ?></tr>
</table>

【讨论】:

  • 请允许我 10 分钟,我会告诉你结果。
  • 抱歉昨晚耽误了家庭时间...我喜欢您构建代码的方式...我也已对其进行了修改...但我仍然收到Array 结果。
  • 这里是结果屏幕截图...snag.gy/s4nj3S.jpg。所有正确字段的第一行是从 db 手动创建的。以下两行是已发布的数据。
  • 我明白了...所以您需要处理与其他输入字段略有不同的数组。给我一点时间来更新我的答案。
  • 谢谢...非常感谢...更新时请告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多