如何从php中的数据库表创建表单下拉列表?
问题描述:
I am trying to code a function which creates a dropdown of school names selected from a database. It is doing fine creating a dropdown but it is not putting anything in the dropdown. Here is the code:
function schoolDD($name, $selected){
$select = '';
if( $selected != null )
{
$select = $selected;
}
$qry = "select *
from school
order by name, id
where display = 'Y'";
$schools = _execQry($qry);
$html = '<select name="'.$name.'" >';
foreach( $schools as $s ){
$html .= '<option value="'. $s['id'] .'"';
if( $select == $s['name'] ){
$html .= 'selected="selected"';
}
$html .= '>'. $s['name'] . '</option>';
}
$html .= '</select>';
return $html;
}
答
Problem solved. It was because in the query I had order before where. It should have been:
$qry = "select *
from school
where display = 'Y'
order by name, id";
Not:
$qry = "select *
from school
order by name, id
where display = 'Y'";
答
Looks OK but hard to say without knowing what _execQry does.
If you add the line
print_r($schools);
after you call _execQry, are you definitely retrieving results from the database?
答
Im glad you found your answer, but i haaattee php and html mixed together like that.
what about tsomethign like this...
<?php
$schools = getSchools();
$selectedSchool = 'sfgsfgd';
$name = 'asdfsafd';
?>
<select name="<?= $name ?>">
<?php foreach( $schools as $s ): ?>
<option value="<?= $s['id'] ?>"<?php if( $s['name'] == $selectedSchool ): ?> selected="selected"<?php endif; ?>><?= $s['name'] ?></option>
</select>