0

I am trying to populate an HTML select list using an array of customer names. I am using the following code, but it does not seem to work. I have a function that query an SQL Server database and gets the names. I know that works fine as I am using it in other code, for some reason when I try to populate the select list it is coming up blank. Would it be better or more efficient to use a for loop? What is the best way to accomplish this?

<select name="customers">
    <?php
    $custNames = getCustomers();
    foreach($custNames as $customers){
        echo '<option value="' . $customers . '">' . $customers . '</option>';
    }
    ?>
</select>
1
  • What do you see when you var_dump() $custNames? It may well be a multi-dimensional array or just not what you think it is Commented Sep 21, 2010 at 15:44

2 Answers 2

3

Have you tried doing a print_r() or var_dump() of $custNames. There's nothing wrong with your foreach loop, so most likely the getCustomers() function is returning a non-array, or an empty array.

And of course, be very careful inserting text that way. A single double-quote in any of the customer names will hose your form:

<option value="John "The Unknown" Doe">John "The Unknown" Doe</option>

At least pass the value portion through htmlspecialchars() to make it a bit safer.

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

2 Comments

Thanks for the help, I found when i used var_dump that it came back empty, when i looked further back I found an error in my typing that did not include my functions. It was an easy mistake but when your looking at something for a while I skipped over it a bunch of times. Thanks for the help, i appreciate it!
Thanks for the tip on htmlspecialchars() also!
0

A foreach loop is perfectly fine, provided that getCustomers() is returning an array (or more specifically, an object that implements the Traversable interface). You may wish to do a var_dump( $custNames ); to check that what you have is in fact an array, otherwise you'll probably want to change the getCustomers() function to return an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.