Dan
Dan

Reputation: 45

php populate option box from database table

I am writing code to register a new project via a html form. I want to be able to click a dropdown box which pulls the values from a table on the database.

At the moment a dropdown box displays but with no values.

PLEASE NOTE: I am a learning the basics so apologies if this is a simple question/answer scenario.

My code is below, any help is appreciated, I connect to the database via a php include script. The table is called 'customers' and the item I want to list is 'name';-

    <?php
$result = mysql_query("SELECT customers FROM name"); 
 echo "<select name='client'>"; 
 while($row = mysql_fetch_assoc($result)) 
 { 
    echo "<option value = '".$row[name]."'>".$row[name]."</option>"; 
 }
 echo "</select>";
?>

Upvotes: 1

Views: 76

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

"The table is called 'customers' and the item I want to list is 'name';" -

Do SELECT name FROM customers instead of SELECT customers FROM name

  • Using mysql_error() to mysql_query()
    would have shown you the error that the table name does not exist.

Plus,
[name] are missing quotes inside them => ['name'] which are being treated as constants.

in

echo "<option value = '".$row[name]."'>".$row[name]."</option>";

as caught and kudos to devdesign

echo "<option value = '".$row['name']."'>".$row['name']."</option>";

However, you are using a deprecated MySQL library. If you are still not getting results, then this could mean that you need to use (and should use) mysqli_ or PDO instead.

Here are a few links on the subject:

Upvotes: 3

Imran Khan
Imran Khan

Reputation: 358

Your code should be. Also note the single quotes within $row['name']. You missed that.

<?php
$result = mysql_query("SELECT name FROM customers"); 
 echo "<select name='client'>"; 
 while($row = mysql_fetch_assoc($result)) 
 { 
    echo "<option value = '".$row['name']."'>".$row['name']."</option>"; 
 }
 echo "</select>";
?>

Upvotes: 2

Related Questions