0

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?

2
  • 2
    There's no reason you need to make two SQL queries in the code. You could easily combine the two: SELECT id,name FROM materials and subsequently, in the loop, only get one result row. Commented Jan 27, 2014 at 3:48
  • Thanks for that. I actually just did that before checking this reply and I found that it was much shorter and looked cleaner. Commented Jan 27, 2014 at 4:12

3 Answers 3

1

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! :-)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is what I eventually realized what to do after looking at my code.
0

I changed the

&&

to a "AND" within the condition and it worked.

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.