How to Code PHP & MySQL to Choose the State

A drop-down box provides programmers with a convenient way to allow readers to choose a state. The drop-down box standardizes data, so all state entries from the user are the same. You use the PHP language to create the drop-down box and you use the MySQL database "State" table to retrieve a list of states.

Instructions

    • 1

      Right-click the PHP file you want to use to retrieve a list of states and select "Open With." Click your PHP editor.

    • 2

      Create the connection to your MySQL database that contains the list of states:

      mysql_connect("localhost", "username", "password") or die(mysql_error());
      mysql_select_db("statedatabase") or die(mysql_error());

      Replace the username and password with your own username and the password you use to connect to the database.

    • 3

      Query the server to retrieve a list of states. The following code queries MySQL for a list of states from the "states" table:

      $states = mysql_fetch_array( "select * from states");

    • 4

      Loop through each returned database result and display a list of entries in a drop-down box:

      <select>
      <?php
      while ($row= mysql_fetch_assoc($states)) {
      echo "<option>";
      echo $row["state"];
      echo "</option>";
      }

Related Searches:

References

Comments

Related Ads

Featured