Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Dec 2005
    Posts
    141
    Thanks
    0
    Thanked 0 Times in 0 Posts

    An Easier way to put a DropBox of a tables-field entrys

    PHP Code:
     <?php

    mysql_connect
    (localhost,$user_db,$pass_db);
    @
    mysql_select_db($database) or die( "Unable to select database");
    $query=" SELECT * FROM ca_spots WHERE zone='CA1'";
    $result=mysql_query($query);
    $num=mysql_numrows($result);
    mysql_close();
    $i=0;
    while(
    $i<$num) {
    $zone=mysql_result($result,$i,"zone");
    $spot_name=mysql_result($result,$i,"spot_name");

     echo 
    "<option value=\"$spot_name\">$spot_name</option>";

    $i++;
    }
    ?>
    Iv list that same code in alot of places and im just wondering if theres a way easyer way to make a Dropbox fill with my mySQL database content

  • #2
    Senior Coder NancyJ's Avatar
    Join Date
    Feb 2005
    Location
    Bradford, UK
    Posts
    3,174
    Thanks
    19
    Thanked 66 Times in 65 Posts
    First you should put your DB code in an include file - then you only need to include the file rather than write out all that connection code.

    Then theres a much easier way to write the code that you have there:

    PHP Code:
    $sql "SELECT * FROM ca_spots WHERE zone = 'CA1'";
    $result mysql_query($sql) or die(mysql_error())
    while(
    $row=mysql_fetch_assoc($result))
    {
       echo 
    '<option value = "'.$row['spot_name'].'">'.$row['spot_name'].'</option>';

    And ofcourse you could write it into a function eg.

    PHP Code:

    function dropDownOptions($query$id$value)
    {
        
    $result mysql_query($query);
         while(
    $row mysql_fetch_assoc($query))
         {
            echo 
    '<option value = "'.$row[$id].'">'.$row[$value].'</option>';
          }

    then you would just call it like
    PHP Code:
    dropDownOptions("SELECT * FROM ca_spots WHERE zone = 'CA1'"'spot_name''spot_name'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •