Tom Tom - 5 months ago 10
PHP Question

How can i use a for loop with array for select options?

I am trying to create a form select statement with options created with this loop like so:

<div class="form-group">
<label for="inputType" class="col-md-4 control-label">Type: <span class="error">*</span></label>
<div class="col-md-8">
<select class="form-control" name="type" id="inputType">
<option value="" >Select:</option>
<?php
for ($row = 0; $row < 4; $row++) {
echo '< option value= ' . '"' .$result[$row][1] . '"';
if ($type == $result[$row][1] ){
echo ' selected ';
}
echo '>' . $result[$row][1] . '< /option ><br>';
}
?>
</select><span class="error"><?=$typeErr;?></span>
</div>
</div>
</div>


If I use the exact loop after my PDO select statement, but above the html tag:

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT ptype.* FROM ptype");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

$result = $stmt->fetchAll();


for ($row = 0; $row < 4; $row++) {
echo '< option value= ' . '"' .$result[$row][1] . '"';
if ($type == $result[$row][1] ){
echo ' selected ';
}
echo '>' . $result[$row][1] . '< /option ><br>';
}


It outputs perfectly, like this:

< option value= "member">member< /option >
< option value= "org employee">org employee< /option >
< option value= "org admin employee">org admin employee< /option >
< option value= "org admin member">org admin member< /option >


But within the form, I get nada in my select field's drop down. I had it working somewhat. It was populating the dropdown, but it was giving me the wrong values. Since I've tried to fix it, I can't get anything in the field.

This is driving me nuts!

Answer

Get rid of the space between the open tag and its name

echo '<option value= ' 

And again for closing tags

echo '>' . $result[$row][1] . '</option ><br>';
Comments