Trouble building select with DB results


I am running into some issues building a select dropdown with DB results. Here is what i have

$birds = $selectbirds->fetch(PDO::FETCH_ASSOC);

<p><label for=\\"Aid\\">Select Animal</label> <select name=\\"Aid\\">";
		foreach ($birds as $bird) {
		 	$output .= "<option value=".$bird['idtag'].">Tag id::".$bird['idtag']."</option>";
	$output .= "</select></p>\

I have all ready tested the query in PMA and it works fine

Thanks in advance

well for starters line 2 of your code there isnt PHP, so it should either be echoed, or outside of the PHP tags.

the next thing is that fetch only returns 1 row, not all rows. so your foreach should be a while($bird = $selectbirds->fetch(PDO::FETCH_ASSOC)) { instead.

The third thing is that there’s no quotes around your option’s value.

Try this:

// EDIT ah yes, fetchAll as Starlion spotted ...

$birds = $selectbirds->fetchAll(PDO::FETCH_OBJ);

$output = "<p><label for='Aid'>Select Animal</label> <select name='Aid'>";
        foreach ($birds as $bird) {
             $output .= "<option value='$bird->idtag'>Tag id:: $bird->idtag </option>" . PHP_EOL;
    $output .= "</select></p>" . PHP_EOL ;

Use object notation with FETCH_OBJ and then you do not need all that string concatenation which you do with arrays, and its easier to read.

Single html/js quotes inside double quotes is one way of doing things, but doubles in doubles means backslashing, and is just another thing to get wrong.

Use the constant PHP_EOL to create line ends so your html output is not one long string.

Creating/debugging html select boxes requires you keep in mind a sanity check, if it does not look/behave correctly then look at the html source code of the page, that might reveal that you made a slight error but forgot to close a quote or an </option>. It is easily done.

Hey there,

i still have had no luck with generating the list. Now it is generating 13 empty “<option value=‘’>Tag id:: </option>” i am not sure where it is getting 13 from. Because even PMA is only returning 4 rows. i used the above code.