1

ive got number of textboxes that will be filled in with name from database.

i create 5 textinputs, using for.. loop

for($i=1; $i<=5; $i++) {
  echo '<input type="text" value="">';
} 

my question is how do i enter the names to the each textboxes dynamically.

i tried:

$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'].'">';
    }
} 

if there are 3 names in database, it will only show 3 instead of 5 textboxes? i want it shows all the textboxes even if the rest of textboxes will be blank.

sample textboxes
1. names
2. names
3. names
4. ------
5. ------

3 Answers 3

2

remove the inner while loop.

$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']:''.'">';
}

of course, better check count of the returned rows, and do not call fetch_assoc() after you've displayed the 3 rows, just output the next 2

Sign up to request clarification or add additional context in comments.

Comments

1

Not always a big fan of using function returns and setting a variable inside an if statement, but this should do what you want:

$q = $db->query("SELECT * FROM att WHERE id_bs_res='$id_bs_res'");  

for($i=1; $i<=5; $i++) {
    if($r = $q->fetch_assoc()) {
        echo '<input type="text" value="'.$r['att_name'].'">';
    } else {
        echo '<input type="text" value="">';
    }
} 

Basically, if there's a valid row, it will echo an input box with the proper values, if there isn't it will simply echo a blank box.

1 Comment

This is effectively the same as Darhazer's answer, just without using a ternary
0

Maybe you can use this: http://php.net/manual/en/control-structures.foreach.php I think that solves all youre problems :) (if i'm correct)

Oh, and I don't understand youre last question? Do you want to show atleast 5 boxes, even when there are only 3 names? Or not?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.