I have a Query that looks something like this (I know its vulne开发者_运维技巧rable to sql injection, its just a template):
$db = mysql_connect("host","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT *"
. " FROM Student" ;
$result = mysql_query($sql);
$students = mysql_fetch_assoc($result);
$numRows = mysql_num_rows($result);
Then I have this form:
<form name="form" id="form" method="post" action="page">
<select name="student" id="student">
<?
for ($i=0;$i<=$numRows;$i++){
echo "<option>" . $students['StudentID'] . "</option>";
}
?>
<option selected="selected">Please select a student</option>
</select>
This should print something like a drop down box with all the values from the table as items. However, I get a drop down box with 6 of the same items, in this case, I get 6 student Id's, but they are all the same ID. I have six students in the db, and I would like to display each of them as an option. What am I doing wrong?
TIA
Have a look at the examples of mysql_fetch_assoc
. It will only return one record. In order to get all of them, you have to use it in a loop, e.g.:
$students = array();
while(($student = mysql_fetch_assoc($result))) {
$students[] = student;
}
and later:
<?php foreach($students as $student): ?>
<option><?php echo $student['StudentID']; ?></option>
<?php endforeach; ?>
or with a for
loop (but it is not necessary if you don't need a counter):
<?php for($i = 0; $i < numRows; $i++): ?>
<option><?php echo $students[$i]['StudentID']; ?></option>
<?php endfor; ?>
(Note: I use the alternative syntax for control structures which imho is much more readable when mixing HTML and PHP)
精彩评论