2017-10-12 55 views
0

插入表中的多個列我有以下的HTML代碼:如何從下拉字段

<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"> 
Faculty ID:<input type="text" name="fid" id="fid" value=""> 
<span class="error">*</span><br><br> 
Sunday: <select name="sun[]" id="sunday" multiple="multiple"> 
    <option value="11">8:15-9:15</option> 
    <option value="12">9:15-10:15</option> 
    <option value="13">10:15-11:15</option> 
    <option value="14">11:15-12:15</option> 
    <option value="15">12:15-1:15</option> 
    <option value="16">1:15-2:15</option> 
    <option value="17">2:15-3:15</option> 
    <option value="18">3:15-4:15</option> 
    <option value="19">4:15-5:15</option> 
    </select> 
    <span class="error">*</span><br><br> 
<button type="submit" value="Submit">Submit</button> 
</form> 

我如何可以插入從下拉列表(星期日)爲不同的列中選擇多個值嗎?

例如,如果8:15-9:15被選中,那麼其值必須輸入到s1列到表中,如果9:15-10:15,然後它必須被輸入到的s2柱我的MySQL表等等。

回答

0

入門所選變量從下拉列表

$sunday = array('-select time--', '8:15-9:15', '9:15-10:15' and so on); 
$selected_key = $_POST['sun']; 
$selected_val = $sun[$_POST['sun']]; 

將數據插入到不同的表

$query = "INSERT INTO `" . $selected_val . "` 
VALUES ('".$x"','".$y."','".$z."')"; 
0

可以存儲的下拉選項到一個數組,其值的鍵是列名。然後你可以檢查選擇了哪些選項,並將相應的列添加到另一個數組中。然後你插入數據:

$columns = array(
     "8:15-9:15" => s1, 
     "9:15-10:15" => s2, 
     "10:15-11:15" => s3, 
     "11:15-12:15" => s4, 
     "12:15-1:15" => s5, 
     "1:15-2:15" => s6, 
     "2:15-3:15" => s7, 
     "3:15-4:15" => s8, 
     "4:15-5:15" => s9 
    ); //create a map between the options and column names 

    //retrieve the selected options to an array 
    $selectedOptions = $_POST['sun']; 

    $selectedColumns = array(); 

    if(count($selectedOptions)) { 
    //add the column name for each selected option to an array 
    foreach ($selectedOptions as $option) { 
     $selectedColumns[] = $columns[$option]; 
    } 
    // create a string with the columns names 
    $columnsToInsert = implode(", ", $selectedColumns); 
    // create a string with the selected options 
    $valuesToInsert = implode("', '", $selectedOptions); 
    // create the query string 
    $query = "INSERT INTO your_table('$columnsToInsert') VALUES ('" . $valuesToInsert ."')"; 
    // then you execute the query 
    } 
相關問題