Jump to content

Recommended Posts

I've created this simple function that when called should generate a drop down select form element. However, it's not cooperating!

 

<?php
function search_form() {

// do sql query for data
$sql = "SELECT category FROM categories";
$results = mysql_query($sql) or die(mysql_error());
$info = mysql_fetch_array($results);
// echo essential HTML to start form
echo "<form method='POST' action='search.php'>
<select name='category>";

// now loop through the query results to create selections
foreach($info as $month) {
	echo "<option value='$month' name='$month'>$month</option>\n\r";

  }
    echo "</select>";
echo "<input type='submit' name='search' value='Search'>\n
</form>";
}
?>

 

It's not displaying all the category names in the list, just the first one. There's three:

 

Test Cat1

Test Cat2

Test Cat3

 

All that displays is Test Cat1. The foreach loop should create a new <option> for each one in the array. But it's not. :(

mysql_fetch_array() only gets one result each time it is called. You need to use a while loop.

 

<?php
function search_form() {
  echo "<form method='POST' action='search.php'><select name='category>";
  $sql = "SELECT category FROM categories";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      while($row = mysql_fetch_assoc($result)) {
        echo "<option value='{$row['category']}' name='{$row['category']}'>{$row['category']}</option>\n\r";
      }
    }
  }
  echo "</select>";
  echo "<input type='submit' name='search' value='Search'>\n</form>";

?>

Thanks, Thorpe. Only question now is why does it only display Cat2 and Cat3 in the dropdown? In viewing page source it shows all 3 category options. But, in the display of the actual dropdown only those two are in the select box.

 

http://www.lenderfish.com/search-test.php

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.