Reputation: 13
Ok so here is my code:
$select_status = 0;
$select_status = "<select name='status'>\n";
$select_status .= "<option value=''>SELECT ONE</option>\n";
$sdataset = mysql_query("SELECT id, name FROM phponly_category") or die(mysql_error());
while($srow=mysql_fetch_assoc($sdataset)) {
echo implode(", ", $srow);
echo "<br />";
$select_status .= "<option value='".$srow['name']."'";
$select_status .= ">".$srow['name']."</option>\n";
} // end while loop
echo "out of the loop";
$select_status .= "</select>\n";
// now insert the <select> list control into the page
echo $select_status;
The code works fine until the last row when it breaks. I cannot get the echo $select_status printed. I have tried to see what is going on with the SQL query results by printing each row but everything looks fine there. For some reason, at the last row the while loop breaks and even the code after while loop doesn't get executed.
Upvotes: 1
Views: 1286
Reputation: 8590
Use mysql_fetch_assoc
so you can get the data using the field name as the key.
<?php
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('test');
$select_status = "<select name='status'>\n";
$select_status .= "<option value=''>SELECT ONE</option>\n";
$sdataset = mysql_query("SELECT id, name FROM phponly_category") or die(mysql_error());
while($srow=mysql_fetch_assoc($sdataset)) {
$select_status .= "<option value='".$srow['name']."'".">".$srow['name']."</option>\n";
} // end while loop
$select_status .= "</select>\n";
echo $select_status;
?>
Note: The use of this extension is discouraged. Take a look at mysqli or PDO.
Upvotes: 0
Reputation: 1930
I personally don't like to echo out html code, if your goal is to do validate whether there's result comes out of the query, you can do something like this
<?php
$sdataset = mysql_query("SELECT id, name FROM phponly_category");
if (mysql_num_rows($sdataset) > 0) {
?>
<select name='status'>
<option value=''>SELECT ONE</option>
<?php
while($srow = mysql_fetch_array($sdataset)) {
?>
<option value='<?php echo $srow['name'] ?>'><?php echo $srow['name'] ?></option>
<?php } // end while loop ?>
</select>
<?php
} // end of if
else {
// Whatever you wanna put here
}
?>
EDITED: There's a typo at mysql_num_rows
, try this one again
Upvotes: 0
Reputation: 360572
The or die()
on your while() loop will actually kill the script when you read the end of the result set. mysql_fetch will return false, triggering the or die()
.
While checking for errors is good on queries, you can't do it like this on the fetching part, because you get false positives like this.
Upvotes: 1
Reputation: 8078
Don't do the or die(mysql_error())
portion in the while test...do it before.
if($sdataset==false) {
die(mysql_error());
}
while($srow=mysql_fetch_array($sdataset)) {
$select_status .= "<option value='".$srow['name']."'".">".$srow['name']."</option>\n";
} // end while loop
Upvotes: 1