-4

This is my list box sample code

<form id="myForm" action="somePage.php" method="post">
<p>myList<br>
<select name="select">
<option value="Option 1" selected>---</option>
<option value="Option 2">sel1</option>
<option value="Option 3">sel2</option>
<option value="Option 4">sel3</option>
</select>
</p>
</form>

But the problem is that i would like to fill the list with the result of a query. Leaving out for a moment the query, the real point is "How can i print the <option value= ..." programmatically so that with a for cycle i can fulfill the list? For example i thought something like this

<form id="myForm" action="somePage.php" method="post">
    <p>myList<br>
    <select name="select">
<?php
  for(i;i < myQueryResultArray length;i++){
  $counter = i;
  echo <option value="Option $counter">$myArrayValue[i]</option>
}
?>

</select>
    </p>
    </form>

This is for sure wrong but that's the idea i had. It may be correct with proper syntax? Or better other ways? Thanks

r4id4
  • 5,877
  • 8
  • 46
  • 76
  • by the way, why didn't you post correct code? at least with correct syntax? – Fallen Feb 18 '14 at 16:30
  • it's not the code i'm using, it's just a piece of code i wrote on the fly to specify the idea of what i mean to do. Even though it's not correct (and i said it in my post) the important is to get the idea, that i think it's clear or not? – r4id4 Feb 18 '14 at 16:33
  • 5
    @Fallen if he knew the right syntax there wouldn't be a question – Sterling Archer Feb 18 '14 at 16:34

2 Answers2

0
$res = $db->query($query);
foreach($res as $item) {
    ?>
    <option value = "<?=$item['key1']?>"><?=$item['key2'] ?></option>
    <?php
}
General_Twyckenham
  • 2,161
  • 2
  • 21
  • 36
  • Why do you choose to use PHP short tags instead of escaping HTML? – Ruben Feb 18 '14 at 16:36
  • @RUJordan He said he was putting aside the query for the moment. For the purposes of the answer, any query will do. – General_Twyckenham Feb 18 '14 at 16:37
  • @Ruben I'm pretty sure that it's a better practice. I think it makes for cleaner code, in my own opinion. – General_Twyckenham Feb 18 '14 at 16:39
  • yeh the query is not important now just wanted to see if i could fill the list within php code. Will this work? no echo or print to stamp the string? it seems easy so :) – r4id4 Feb 18 '14 at 16:39
  • @ObiWanKeNerd Lol as far as I can tell, this code will satisfy your needs. The quick `= ?>` is a shortcut that basically echo's what you put into it. You can read further about it here: http://stackoverflow.com/questions/2020445/what-does-mean-in-php – General_Twyckenham Feb 18 '14 at 16:48
0

You'd want a for loop like this

for($i = 0; $i < sizeof($myQueryResultArray);$i++){ //note the changes here
    //declare variables with $
    //sizeof() will return length
    echo "<option value='Option $i'>$myArrayValue[$i]</option>"; //notice the quotes
}
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118