将数据库中的选定值保存为id

时间:2014-12-24 10:04:31

标签: php mysql codeigniter

我有两个表,如员工编辑其详细信息department_id,在数据库中保存为0

employee                       department
id| name|department_id     id|department_name
1 |abc  |1                  1|HR    
2 |xyz  |4                  2|Finance   
3 |asd  |3                  3|Developer      

和此视图部分

<tr>
    <th> Department </th>
    <td> 
        <SELECT name="department_id" style="width:180px;" >
            <?php 
            foreach($departments as $row): ?>
            <option value="<?php $employee['department_id'] ;?>"
            <?php  if ($row['id']== $stakehholder['department_id'])
            {
            echo 'selected';
            }
            ?>>
            <?php echo $row['department_name'];?>
            </option> 
            <?php endforeach ?>
        </SELECT>
    </td>
    <td> <?php echo form_error('department_id'); ?> </td>
</tr>     

编辑0值后,在数据库中获取存储

3 个答案:

答案 0 :(得分:4)

忘记回声 <option value="<?php $employee['department_id']; ?>"

<SELECT name="department_id" style="width:180px;" >
    <?php foreach($departments as $row): ?>
            <option value="<?php echo $row['department_id']; ?>"
            <?php if ($row['department_name']== $stakehholder['department_id']) {
                echo 'selected';
            }
           ?>>
        <?php echo $row['department_name']; ?>
        </option> 
        <?php endforeach ?>
    </SELECT>

答案 1 :(得分:1)

更新后的行如下

<option value="<?php echo $employee['department_id'] ;?>






<tr>
    <th> Department </th>
    <td> 
        <SELECT name="department_id" style="width:180px;" >
            <?php 
            foreach($departments as $row): ?>
            <option value="<?php echo $employee['department_id'] ;?>"
            <?php  if ($row['department_name']== $stakehholder['department_id'])
            {
            echo 'selected';
            }
            ?>>
            <?php echo $row['department_name'];?>
            </option> 
            <?php endforeach ?>
        </SELECT>
    </td>
    <td> <?php echo form_error('department_id'); ?> </td>
</tr>

答案 2 :(得分:1)

你忘了在选项值属性中回显department_id,其次你要比较名称和id,如果id是int而且名字不是,那么它永远不会匹配。

尝试更新的代码:

<SELECT name="department_id" style="width:180px;" >
     <?php 
     foreach($departments as $row): ?>
     <option value="<?php echo $row['department_id'] ;?>"
     <?php  if ($row['department_id']== $stakehholder['department_id'])
     {
        echo 'selected';
     }
    ?>>
    <?php echo $row['department_name'];?>
    </option> 
    <?php endforeach ?>
</SELECT>