Hi there!

I'm new to PHP and I'm having trouble getting past this obstacle:

We're using a MySQL database and there is a particular field within a table that I'd like to compare to a dropdown. for example..

The field within the table is "state". It can contain the two letter abbreviation for any of the 50 states. On the page is a dropdown listing all of the 50 states and the values of the options within the dropdown are the two digit abbreviation of the states. When the page loads and pulls data from the database and populates editable fields, such as other text boxes, etc. How can I iterate through the dropdown and have the one that matches the entry within the database be "selected"?

Your time is appreciated. Thanks!

    Should be relatively simple:

    function selectKey($arrayToSearch,$valueToFind)
    {
    	$theKey = array_search($arrayToSearch,valueToFind);	//$theKey contains key of the given value if it exists in the array
    	$hasBeenFound = false;	//Just a boolean to indicate whether or not the value was found
    	foreach($arrayToSearch as $key=>$value)	//Go through each key & value in the array, storing the key in $key and value in $value
    	{
    		if($key !== $theKey)	//Check to see if the current key matches the key we're looking for
    		{
    			echo "<option value=\"$value\">$value</option>";	//No, doesn't match
    		}
    		else
    		{
    			echo "<option value=\"$value\" selected=\"selected\">$value</option>";	//Yes, it matches so select this option
    			$hasBeenFound = true;
    		}
    	}
    	return $hasBeenFound;
    }
    

    Didn't try it out, but I don't see any glaring errors right now (although I'm pretty tired at the moment)

    Hope this helps 😉

      I assume you you probably don't have your html states dropdown being rendered dynamically. So the solution, to clarify a bit here, is to create an array of your state values first:

      
      $states = array(
      "AK"=>"Alaska",
      "AR"=>"Arkansas"
      );
      

      ...and so on...

      the => notation simply means, in the case of "Alaska", that "AK" is the associated key for "Alaska."

      Now you can render your dropdown programatically...

      You can use ScubaKing22's very good and generic function to produce the options for your select box, or to just show you a quick but potentially less confusing aspect...

      //get your two-letter abbreviation value from database.
      $dbState = //code to get it that you must know how to write.
      
      echo "<select name='state'>\n";
      foreach ($states as $abbreviation => $state)
      {
      	echo "<option value='$abbreviation'";
      	echo ($abbreviation == $dbState) ? " selected" : "";
      	echo ">$state</option>\n";
      }
      echo "<select>\n";
      

      Code not tested.

        THANK YOU THANK YOU THANK YOU

        I THANK YOU FROM THE BOTTOM OF MY HEART!!!!

        Man I was dying on that hangup and just could NOT think of a way around.

        Thanks for your help.

          Hi there,

          New issue coming up after that iteration that I hope you can help me with.

          Here's what I'm doing...

          I'm pulling phone number data from a MySQL database and then, row by row, I am displaying it within a dropdown (Phone Type - for example, "work", "home", etc) and then next to it, a Phone Number that is associated is displayed in a text-box that is editable.

          What I want to be able to do is this:

          If there are say, 4 phone numbers listed, each one will look like this...

          Dropdown Textbox
          [WORK] [Phone Number ]
          [HOME] [Phone Number ]
          [OTHER] [Phone Number ]
          [PAGER] [Phone Number ]

          Here is HOW I am doing this right now...

          <?php
          // pull the PHONE info
          $phone_pull = "SELECT * " .
          "FROM PHONE " .
          "WHERE CONTACT_FK=" . $_GET['contact_id'];
          $pulled_phone = mysql_query($phone_pull,$conn) or die('Could not perform the search on phone; ' . mysql_error());
          
          //to iterate through the "PHONE TYPE" options I have to create an array and then compare to it
          $phone_type = array(
          "WORK"=>"Work",
          "HOME"=>"Home",
          "CELL"=>"Cell",
          "PAGER"=>"Pager",
          "FAX"=>"Fax",
          "OTHER"=>"Other"
          );
          
          //Now, run through each row and display the desired fields for each row produced.
          while ($phone_row = mysql_fetch_array($pulled_phone, MYSQL_ASSOC))
          	     {
          	     echo '<tr>';
          	     echo '<td noWrap width="50%" align="right" valign="top"><FONT face="Tahoma" color="#000000" size="2">';
          
               // iterate through the CONTACT TYPE dropdown using the $phone_type array.
          
          	echo "<P align=\"right\"><select id=\"phone_type\" name=\"phone_type\" tabindex=\"36\">\n";
          	foreach ($phone_type as $phone_type4db => $phone_typename)
          	{
          	echo "<option value='$phone_type4db'";
          	echo ($phone_type4db == $phone_row['PHONE_TYPE']) ? " selected" : "";
          	echo ">$phone_typename</option>\n";
          	}
          echo "</select>\n";
          
               echo '</FONT></td>';
          
               echo '<td  noWrap width="50%" align="left" valign="top"><FONT face="Tahoma" color="#000000" size="2">';
          	 echo '<P align="left">';
          	 ?>
          	<INPUT type="text" id="phone_num"  name="phone_num" maxLength="50"  size="20" tabindex="37" value="<?php echo $phone_row['PHONE_NUM']; ?>">
          			<?php
              	     echo '</FONT></P></td>';
              	     echo '</tr>';
             }
          
          ?>
          
          

          My question is this: With this method, Since the rows are simply run through...how will I be able to take any data that the user updates (for example, changing the "TYPE" or changing the phone number for any one of those listed, and then using a MySQL UPDATE, put the new information in the database with the associated record?

          Thanks once again from a grateful newbie...

          -tryxxter

            Any chance your PHONE table has auto-incremented ids? If it doesn't, it will need to in order for your users to update it properly since possible duplicates can exist in this scenario.

            Simply insert it somewhat like this:

            echo "<select name=\"phone_type_{$phone_row['PHONE_ID']}\" tabindex=\"36\">

            Do the same for:

            <INPUT type="text" id="phone_num" name="phone_num_<php echo $phone_row['PHONE_ID']?>"...

            This will make sure that each iteration is "stamped" with the id of the current PHONE record.

            In my experience the easiest way to process the update is to iterate thorugh every POST pair:

            //Dang, I keep seeing bugs in this code. make sure you test it 😃

             $searchKey = "phone_num_" ;  
            foreach ($_POST as $key => $value) { if (strpos($key, $searchKey) !== false) { //this is a POST pair we are interested in. Now let's extract the id. $id = substr($key, strlen($searchKey)); /*test the above and add or subtract from the len statement if it's not extracting the id from the end*/ //Now you can can send a query like: $sql = "UPDATE PHONE SET PHONE_NUM = '$value' WHERE PHONE_ID = '$id'"; $sql = "UPDATE PHONE SET PHONE_TYPE = '" . $_POST['phone_num_' . $id] . "' WHERE PHONE_ID = '$id'"; } }

              Hi there!

              Yes, thankfully the PHONE_ID field is an auto-incremented type. So all id's are unique... I will try your technique and let you know how it works...

              Thanks once again...

              -tryxxter

                dood.... YOU ROCK!!!! 😃

                This is what I added based on your response to me...

                <?php
                //^^^^^^^^^^^ PHONE NUMBER UPDATE SECTION
                $searchKey = "phone_num_" ;
                 foreach ($_POST as $key => $value)
                 {
                    if (strpos($key, $searchKey) !== false)
                    {
                        //this is a POST pair we are interested in. Now let's extract the id.
                         $id = substr($key, strlen($searchKey));
                        /*test the above and add or subtract from the len statement
                        if it's not extracting the id from the end*/
                        //Now you can can send a query like:
                 $update_phone_sql = "UPDATE PHONE SET PHONE_NUM ='" . $value . "', PHONE_TYPE='" . $_POST['phone_type_' . $id]. "' WHERE PHONE_ID = '" . $id . "'";
                         mysql_query($update_phone_sql,$conn);
                        echo 'Phone id: ' . $id . ' Key: ' . $key . ' TYPE: ' . $_POST['phone_type_' . $id] .
                        ' value: ' . $value . ' <br />';
                    }
                 }
                //^^^^^^^^^^ END PHONE NUMBER UPDATE SECTION
                
                ?>
                

                It works FLAWLESSLY!!!! Thanks so much for savin' mah butt....AGAIN.
                🆒

                -tryxxter

                  Glad I could help, I appreciate it when I see guys that actually try and don't expect it handed to them or will take the tips and work it out (ie you.)

                  😃

                    Write a Reply...