将动态字段值插入MySQL表

时间:2013-12-22 20:10:22

标签: php mysql pdo

如果从下拉菜单中选择了值Others- Not Listed,则表单中会显示动态输入字段。我试图通过php pdo将这些值插入到名为courses_selection_list的mysql表中。我将同时插入course_idcourse_name。此值位于div .hideNewCourse内。但由于值在动态输入字段内,因此不确定如何操作。直播DEMO

<form>
<div id="course_catalog">
<div id="course_1">
<label>Course # 1</label>
<br>
<label>Course Name:</label>
<select id="coursename_1" class="course_list" name="coursename_1">
<option value="">--- Select ---</option>
<option value="1">Math</option>
<option value="2">English</option>
<option value="3">Science</option>
<option value="4">Other- Not Listed</option>
</select>
<div class="hideNewCourse" style="">
Add Course Name to List:
<input id="new_course_name_50" class="new_course_name" type="text" name="new_course_name[]">
<input id="new_course_id_50" class="new_course_id" type="hidden" readonly="readonly" name="new_course_id[]" value="50">
</div>
</div>
<br>
<div id="course_2">
<label>Course # 2</label>
<br>
<label>Course Name:</label>
<select id="coursename_2" class="course_list" name="coursename_2">
<option value="">--- Select ---</option>
<option value="1">Math</option>
<option value="2">English</option>
<option value="3">Science</option>
<option value="4">Other- Not Listed</option>
</select>
<div class="hideNewCourse" style="">
Add Course Name to List:
<input id="new_course_name_51" class="new_course_name" type="text" name="new_course_name[]">
<input id="new_course_id_51" class="new_course_id" type="hidden" readonly="readonly" name="new_course_id[]" value="51">
</div>
</div>
</form>

表:courses_selection_list

+-----------+-------------------+
| course_id |    course_name    |
+-----------+-------------------+
|         1 | Math              |
|         2 | English           |
|         3 | Science           |
|         4 | Other- Not Listed |
+-----------+-------------------+

1 个答案:

答案 0 :(得分:1)

请尝试以下操作,以便将这些值提交到您的表格中:

if (isset($_POST['submit'])) {
//I used `new_course_name` as the loop termination condition, 
//but any of the 2 keys would have worked
for ($i = 0; $i < count($_POST['new_course_name']); $i++) {
    $new_course_name = $_POST['new_course_name'][$i];
    $new_course_id = $_POST['new_course_id'][$i];

//here, inside the loop, run the database query using the 2 values above    
$query_init3 = $db_con->prepare("INSERT INTO courses_selection_list (course_id, course_name) VALUES(:new_course_id, :new_course_name);");
$query_init3->execute(array(
    "new_course_id" => $new_course_id,
    "new_course_name" => $new_course_name
));
}
}