多个选项并保持选定的值

时间:2017-04-19 18:45:23

标签: php html database validation mysqli

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

这是我的代码:

<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,我可以稍后更改,但无论查询失败还是成功,我似乎无法保留所选选项。

1 个答案:

答案 0 :(得分:0)

我稍微清理了你的代码并重写了它,以便你可以测试提交表单时会发生什么。试试这个并确保表单输出您选择的正确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()函数将字符串转换回数组,以便根据您的评论在新列中显示每位治疗师。< / p>

假设您将这些值存储在变量$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>