我的表单包含输入字段,其中包含从mysql表填充的值。在我的select语句中,我将这些值传递给字段。该表名为person
,具有唯一标识person_id
和外键academy_id
。每个人都有一个状态active
或inactive
存储在字段名称person_status
中。我很难从person_status
为每个人提取值。如何在选择查询中显示每个人的状态? EXAMPLE
选择要填充的查询
<?php
$id = 15;
$db_select2 = $db_con->prepare("
SELECT a.name,
a.academy_id,
p.person_id,
p.person_status,
p.first_name
FROM academy a
LEFT JOIN person p ON a.academy_id = p.academy_id
WHERE a.academy_id = :id
");
if (!$db_select2) return false;
if (!$db_select2->execute(array(':id' => $id))) return false;
$results2 = $db_select2->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results2)) return false;
$result2 = '';
$s = 1;
echo "<table>";
echo "<tbody>";
foreach ($results2 as $value2){
echo "<tr>";
echo "<td>Name #".$s."<input type=\"hidden\" name=\"person_id_".$s."\" value='". $person_id = $value2['person_id']."' readonly=\"readonly\"/><input id=\"person_fname_".$s."\" name=\"person_fname_".$s."\" placeholder=\"Person #".$s." First Name\" type=\"text\" value='" . $value2['first_name'] ."'/></td>";
echo "</tr>";
$s++;
}
echo "</tbody>";
echo "</table>";
?>
希望将此功能集成到select语句中:
<?php
$table_name2 = "person";
$column_name2 = "person_status";
echo "<select name=\"$column_name2\"><option>Select one</option>";
$sql1 = 'SHOW COLUMNS FROM '.$table_name2.' WHERE field="'.$column_name2.'"';
$row1 = $db_con->query($sql1)->fetch(PDO::FETCH_ASSOC);
$selected1 = '';
foreach(explode("','",substr($row1['Type'],6,-2)) as $option) {
if ($status == $option){
$selected1 = "selected=selected";
}else{
$selected1='';
}
echo "<option value='$option'" . $selected1. ">$option</option>";
}
echo "</select></br>";
?>
答案 0 :(得分:1)
只获取一次选项(无需为每个人重复此选项):
$sqlStatuses = 'SHOW COLUMNS FROM '.$table_name2.' WHERE field="'.$column_name2.'"';
$rowStatuses = $db_con->query($sql1)->fetch(PDO::FETCH_ASSOC);
$personStatuses = explode("','",substr($rowStatuses['Type'],6,-2));
然后,走过那些人
foreach ($results2 as $value2) {
// Your code
echo "<tr>";
echo "<td>Name #".$s."<input type=\"hidden\" name=\"person_id_".$s."\" value='". $person_id = $value2['person_id']."' readonly=\"readonly\"/><input id=\"person_fname_".$s."\" name=\"person_fname_".$s."\" placeholder=\"Person #".$s." First Name\" type=\"text\" value='" . $value2['first_name'] ."'/></td>";
// Added
echo '<td><select name="person_status_'.$s.'">';
foreach($personStatuses as $option) {
echo '<option value="'.htmlspecialchars($option).'" ';
if ($value2['person_status'] == $option) {
echo 'selected="selected"';
}
echo '>' . htmlspecialchars($option) . '</option>';
}
echo '</select></td>';
// Your code again
echo "</tr>";
$s++;
}
将此构建为一个SELECT查询是不必要的复杂(尽管可能,但会为您提供不可读的代码)。
哦,看看htmlspecialchars(),如果一个名字包含“-character,你的HTML搞砸了