How to load data on option box in php
I'm having trouble loading the mysql data to the option box using php. Here's my code:
<?php
$con = mysql_connect("localhost","myuname","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mys开发者_运维百科ql_select_db("school", $con);
$idnum= mysql_real_escape_string($_POST['idnum']);
$result = mysql_query("SELECT * FROM student WHERE IDNO='$idnum'");
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<tr>
<td width="30" height="35"><font size="2">*I D Number:</td>
<td width="30"><input name="idnum" type="text" maxlength="5" value="<?php echo $row["IDNO"]; ?>" readonly="readonly"></td>
</tr>
My problem is loading it here:
<td><font size="2">Gender</td>
<td>
<select name="gender" id="gender">
<font size="2">
<option value="<?php echo $line['IDNO']; ?> "><?php $line['GENDER'] ; ?></option>
</select></td></td>
The table looks like this:
IDNO | GENDER
123 | M
321 | F
What am I supposed to do?To load the exact gender corresponding to the IDNO?
Note: You are wrongly using the $line
instead of $row
for the options, hence not getting the result.
Note 2: From your query it looks, you are fetching just one record:
"SELECT * FROM student WHERE IDNO = '$idnum'"
And hence there is no need for the loop (I assume IDNO
is primary key of the table). If however, you want to read all records of the table, your query should be something like this:
"SELECT * FROM student"
How To Go About:
Put the select box before the while
loop:
<select name="gender" id="gender">
Then your while
loop for options:
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<option value="<?php echo $row['IDNO']; ?> "><?php $row['GENDER'] ; ?></option>
Close the while
loop
<?php } ?>
And finally close the select box
</select>
So in all, your code should look something like this (excluding db stuff):
<select name="gender" id="gender">
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<option value="<?php echo $row['IDNO']; ?> "><?php $row['GENDER'] ; ?></option>
<?php } ?>
</select>
If I understood, your script loads two rows instead of one. Anyway, that's kind of weird because you have a very specific query (SELECT * FROM student WHERE IDNO='$idnum'
)... so, why don't you change it to this?: SELECT * FROM student WHERE IDNO='$idnum' LIMIT 1
so that you can now be sure it will load only one row.
bye!
精彩评论