Reputation: 2022
I have a drop down list script in which it is populated from the database. I'm trying to Show the name on the list, but the actual value is the ID of the name. I think it'd be better to show my code to explain what I'm trying to do:
mysql_connect('localhost', 'user', 'pw');
mysql_select_db ("db");
$sqlId = "SELECT id FROM materials";
$sql = "SELECT name FROM materials";
$result = mysql_query($sql);
$resultId = mysql_query($sqlId);
echo "<td><select name='materials'>";
while ($row = mysql_fetch_array($result) && $row2 = mysql_fetch_array($resultId))
{
echo "<option value='" . $row2['id'] . "'>" .
$row['name'] . "</option>";
}
echo "</select></td></tr> ";
Every time I run this, the drop down list is never populated. What am I doing wrong?
Upvotes: 0
Views: 91
Reputation: 1243
I revised your code and now this should work.
mysql_connect('localhost', 'user', 'pw');
mysql_select_db ("db");
$sql = "SELECT id, name FROM materials";
$result = mysql_query($sql);
echo "<td><select name='materials'>";
while($row = mysql_fetch_assoc($result)) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select></td></tr> ";
Good Luck! :-)
Upvotes: 1
Reputation: 3527
Your code makes wrong assumptions about operator precedence.
Here's how your while statement gets evaluated..
while ($row = (mysql_fetch_array($result) && ($row2 = mysql_fetch_array($resultId))) )
The added parentheses show the order in which PHP evaluates the loop statement. $row
never holds an array of values, instead it is assigned a boolean.
Here is a simpler example:
var_dump( $x = 1 && $y = 2 ); // outputs bool(true)
var_dump( $x ); // outputs bool(true)
var_dump( $y ); // outputs int(2)
To solve, you should either rewrite your code to while (($row = mysql_fetch_array($result)) && ($row2 = mysql_fetch_array($resultId)))
or, as you did, use the and
operator (which has a lower precedence).
Upvotes: 0