Coleen
Coleen

Reputation: 33

Can't get dropdown to populate from MySQL database

I would like to create a simple select drop down, to be populated by a table in my MYSQL database. Here is my code:

$q = 'SELECT * FROM Shipmethods';
$result = mysqli_query($connection, $q);

echo '<select name="shipmethod">';

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)); 
{   
    echo '<option value="' . $row['shipmethodid'] . '">' . $row['shipmethoddesc'] . '</option>';
}

echo '</select>';

mysqli_free_result($result); // free up the results

}

There is no connection error, no typos in table name or column names. The HTML output shows that a select option exists, but it is empty. I would like to use mysqli for this.

There seem to be countless topics already on this subject, but as far as I can see, my code matches the correct answers of those already answered questions.

Thanks in advance.

Upvotes: 0

Views: 592

Answers (2)

gview
gview

Reputation: 15361

First off, based on the evidence we have, the most likely issue, other than an empty result set, is the issue that swapnesh identified, which is clearly a logic error. I'm providing this illustration, which simulates the problem to make it clear that it is NOT a syntax error to do what was accidently done here. The misplaced semicolon in essence causes the following block to be entered only after the while loop has been exhausted.

Consider this example:

<?php

$r = array(1,2,3,4);

function fetchit(&$r) {
    return array_pop($r);
}


while ($val = fetchit($r))
{
    echo $val;
} 

This would be the intended use. Now what happens if the script has this code instead?

<?php

$r = array(1,2,3,4);

function fetchit(&$r) {
    return array_pop($r);
}


while ($val = fetchit($r));
{
    echo $val;
}

Trying these you will see that both scripts run without error. Although unnecessary, php does not care if you randomly include an uneeded block somewhere in your script { }, and it also does not care if an if, while, for etc, is followed by a block. It's in fact common practice for people to shorten up code with:

if (//somecondition)
    statement;

Many people frown on that practice but it's legal and programmers use it all the time.

Upvotes: 0

swapnesh
swapnesh

Reputation: 26732

Remove ; from this line, rest code seems fine to me, let me know if it works or not --

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)); 

To

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))

Upvotes: 5

Related Questions