简体   繁体   中英

Pre-Selected Multiselect from MySql DB Using PHP

I have 2 Mysql tables (tbl_subjects AND tbl_courses).

tbl_subjects
id | subject_name |
1  | english      |
2  | maths        |
3  | Physics      |

tbl_courses
id | my_subjects |
1  | 1,3         |

html & php code for Multiselect list

$sql_subjects = mysql_fetch_array(mysql_query("SELECT * FROM tbl_subjects WHERE id IN ( 1,3 )"));

<select name="subjects[]" multiple="multiple" size="7">
<?php
$sql = mysql_query("SELECT * FROM tbl_subjects");
while($row = mysql_fetch_array($sql ))
{
$id = $row['id'];
$subject_name = $row['subject_name '];
?>
<option value="<?php echo $id; ?>" <?php if($sql_subjects['id'] == $id) echo 'selected="selected"'; ?>> <?php echo $subject_name; ?></option>
<?php } ?>
</select>

As you see in the above code, there should be 2 pre selected values, but i only got result of 1st one.You can see in image also 在此处输入图片说明

$sql_subjects=array();    
while($row = mysql_fetch_array(mysql_query("SELECT * FROM tbl_subjects WHERE id IN ( 1,3 )"))){
    $sql_subjects[] = $row['id'];
}

and in your html part

<option value="<?php echo $id; ?>" <?php if(in_array($id,$sql_subjects) echo 'selected="selected"'; ?>> <?php echo $subject_name; ?></option>

It is because the mysql_fetch_array() will generate the first row only. We need to use the loop to retrieve all the rows.

Instead you know the id then why you retrieving again from database use in_array() to check,

<select name="subjects[]" multiple="multiple" size="7">
<?php
    $ids = array(1,2);
    $sql = mysql_query("SELECT * FROM tbl_subjects");
    while($row = mysql_fetch_array($sql)){
        $id = $row['id'];
        $subject_name = $row['subject_name'];
    ?>
    <option value="<?php echo $id; ?>" <?php if(in_array($id,$ids)) echo 'selected="selected"'; ?>> <?php echo $subject_name; ?></option>
    <?php
    } 
?>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM