2011-12-12 76 views
1

我有一個包含選擇表單字段的表單。字段選項由MySQL查詢和PHP回波動態生成: -從數組和MySQL查詢生成動態表單選擇字段

<select name="students" size="10" multiple="multiple"> 
    <?php 
    do { 
    ?> 
    <option value="<?php echo $row_rsStudents['student_id']?>"><?php echo  $row_rsStudents['student_sname1']?> <?php echo $row_rsStudents['student_sname2']?> <?php  echo $row_rsStudents['student_fname']?>: "</option> 
    <?php 
    } while ($row_rsStudents = mysql_fetch_assoc($rsStudents)); 
    $rows = mysql_num_rows($rsStudents); 
    if($rows > 0) { 
     mysql_data_seek($rsStudents, 0); 
     $row_rsStudents = mysql_fetch_assoc($rsStudents); 
    } 
    ?> 
    </select> 

我也有我所分解和循環的數組: -

<?php 
    $studentsids = $row_rsClasses['class_students']; 
    $students = explode(":", $studentsids); 
    for($i = 0; $i < count($students); $i++){ 
    echo "$students[$i]"; 
    } 
    ?> 

但我想的匹配條目,以顯示在選擇字段中選擇。任何幫助感激地讚賞。

回答

0

如果我理解正確,那麼您的學生列表應該在變量$students的第二個代碼片段中突出顯示?

你有另一組所有學生在while循環中的第一個代碼片段中讀取?

要顯示特定用戶是否在數組$students中,您只需檢查用戶標識是否在此數組中。

if (in_array($row_rsStudents['student_id'], $studentsids)) { 
    echo 'selected="selected"'; 
} 

如果特定的學生位於您的數組中,則可以將其嵌入到表單代碼中以插入選定的屬性。

鑑於你的第二個代碼片段首先執行:

<?php 
$studentsids = $row_rsClasses['class_students']; 
// I assume this array contains all IDs that shall be highlighted 
$students = explode(":", $studentsids); 
?> 

然後你的第一個代碼片段顯示了所有學生:

<select name="students" size="10" multiple="multiple"> 
<?php 
// why have you used do while? Do you have an existing row before? 
// using while(): ... endwhile; is just another style, I prefer it in HTML templates 
while ($row_rsStudents = mysql_fetch_assoc($rsStudents): 
?> 
<option value="<?php echo $row_rsStudents['student_id']?>" <?php if (in_array($row_rsStudents['student_id'], $studentsids)) echo 'selected="selected"' ?> > 
    <?php echo $row_rsStudents['student_sname1']?> 
    <?php echo $row_rsStudents['student_sname2']?> 
    <?php echo $row_rsStudents['student_fname']?> 
</option> 
<?php endwhile; ?> 

<?php 
// what was this intended to do? 
// 
//$rows = mysql_num_rows($rsStudents); 
//if($rows > 0) { 
// mysql_data_seek($rsStudents, 0); 
// $row_rsStudents = mysql_fetch_assoc($rsStudents); 
//} 
?> 
</select>