我有一个带有两个表的mysql数据库:
table1 (id, name, emailid)
table2 (id, email)
emailid
与table2.id
我正在尝试创建一个html表单,其中列出了table1的内容,并带有一个下拉框,供用户选择电子邮件字段。电子邮件字段中填充了来自<options>
的{{1}}。
我的问题是:如何检查table2
已选择的值,并在表单加载emailid
时将其设置为保管箱中的已选项?
我已经有了一个解决方案,但我不认为这是正确的方法,并且正在寻找最佳实践方法。
我目前正在进行此操作的方式仅适用于从selected="selected"
拉出的一个项目,但如果超过1,则不会。
到目前为止,这是我的代码:
这是我获取数据的地方:
table1
这是我的HTML:
<?php
$sql = "SELECT table1.id as table1id, table1.name, table2.id as table2id
FROM table1
INNER JOIN table2 ON table1.emailid = table2.id
WHERE table1.id = {$id}";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$items1 = array('table1id' => $row['table1id']
'name' => $row['table1.name']
'table2id' => $row['table2id']);
$sql = "SELECT id, email FROM table2";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_array($result)) {
$items2[] = array('id' => $row['id'],
'email' => $row['email'],
'selected' => ($row['id'] == $items1['table2id']) ? ' selected="selected" ' : '');
}
?>
这是表单的更新方式:
<tr>
<td><?php echo $items1['name']; ?></td>
<td><input type="hidden" name="table1id" value="<?php echo $items1['table1id']; ?>" />
<?php echo $items1['table1id']; ?></td>
<td>
<select name="email">
<?php foreach ($items2 as $item2): ?>
<option value="<?php echo $item2['id']; ?>"<?php echo $item2['selected']; ?>>
<?php echo $item2['email']; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
答案 0 :(得分:0)
修改强> 现在你已经编码了其他东西。
// Lets make our table2 the primary so we can organize our values in the $items array.
$sql = "SELECT table1.id as table1id, table1.name, table2.id as table2id, table2.email
FROM table2
LEFT JOIN table1 ON table2.emailid = table1.id";
// Do you need this WHERE? I'm thinking not.
// WHERE table1.id = {$id}";
$items = array();
while($row = mysqli_fetch_array($result)) {
// This will get set every time through the loop, but this is ok.
// You can check to see if its set and then set or not set.
$items[$row['table1id']]['name'] = $row['name'];
// We will keep appending email values here to the table1id array.
$items[$row['table1id']]['emails'][] = $row['email'];
}
让我们做HTML标记,因为我们已经为我们提供了一个很好的数组中的所有项目。
<?php foreach($items as $id => $item): ?>
<tr>
<td><?php echo $item['name']; ?></td>
// Do you really need this hidden field?
<td><input type="hidden" name="table1id" value="<?php echo $id; ?>" /><?php echo $id; ?></td>
<td>
// Updated this to be unique for each id iteration.
<select name="email_<?php echo $id; ?>">
// Might want to consider a is_array() check on this value.
<?php foreach ($item['email'] as $email): ?>
<?php $selected = $email == $_POST['email_'. $id] ? ' selected="selected"' : ''; ?>
<option value="<?php echo $email; ?>"<?php echo $selected; ?>>
<?php echo $email; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php endforeach; ?>
我没有对此进行过测试,因此可能无法复制和粘贴。但我认为这可以让你现在正确行事。