我从数据库中得到了许多用名字填写的文本框。
我创建了5个文本输入,用于。。环
for($i=1; $i<=5; $i++) {
echo '<input type="text" value="">';
}
我的问题是如何动态地为每个文本框输入名称。
我试过:
$q = $db->query("SELECT * FROM att WHERE id_bs_res='$id_bs_res'");
for($i=1; $i<=5; $i++) {
while($r = $q->fetch_assoc()) {
echo '<input type="text" value="'.$r['att_name'].'">';
}
}
如果数据库中有3个名称,它将只显示3个而不是5个文本框?
我希望它显示所有的文本框,即使其余的文本框将是空白的。
sample textboxes
1. names
2. names
3. names
4. ------
5. ------
最佳答案
移除内部while循环。
$q = $db->query("SELECT * FROM att WHERE id_bs_res='$id_bs_res'");
for($i=1; $i<=5; $i++) {
$r = $q->fetch_assoc();
echo '<input type="text" value="'.isset($r['att_name'])?$r['att_name']:''.'">';
}
当然,最好检查返回行的计数,在显示了3行之后不要调用fetch_assoc(),只输出下2行