Jeremy
Jeremy

Reputation: 131

How do I get a value from dynamically created form in a dropdown menu using PHP?

I'm trying to build an application that will direct a user to a different website based upon what zip code they enter. In order to narrow it down, in some instances, a user may need to select from a dynamically created drop down list of street names. The application uses PHP and a mySQL database. The issue that I'm having is detailed in the code comments under the PHP section. If possible, please provide a PHP driven solution. If jQuery, Javascript, AJAX, etc. are the only alternatives, please give me some example of how I would implement it with this example. Thanks!

Here's a snippet of the HTML:

<div id="mybox">
<form method="post">
<input type="text" name="zipcode">
<input type="submit" value="Enter Zip Code" name="submitzip">
</form>
</div>

Here is the PHP called by clicking the Submit button:

<?php
if (isset($_POST['submitzip'])) {
    ZipLookup(); }

function ZipLookup() {
$zipcode = $_POST["zipcode"];
$zipcode = trim($zipcode);

if (strlen($zipcode) != 5) {
  echo ("<strong>Please enter a valid five digit Zip Code.</strong>");
}
else {

$servername = "ip here";
$username = "username here";
$password = "password here";
$dbname = "dbname here";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT ZipCode, StreetName, URL FROM db table here WHERE ZipCode ='$zipcode'";
$result = $conn->query($sql);

if ($result->num_rows > 1) {
   echo '<hr><p><strong>We service more than one area in ' .$zipcode. '. Please select your street name.</strong></p>';
   echo '<form method="post">';
   echo '<select name="streetname">';

     while($row = $result->fetch_assoc()) {
           echo '<option value="' . $row["URL"] . '">' . $row["StreetName"] . '</option>'; 
     }
        echo '</select> <input type="submit" value="Submit" name="submitname"> </form>';
        echo '<p>If your street name is not listed, please contact us.</p>';


 // THIS IS WHERE I HAVE PROBLEMS... Values from dropdown don't appear to be stored. When running var_dump, PHP exports the array from the first button. Clicking the dynamic submit button just reloads the page.

    if (isset($_POST['submitname'])) {
         $url = $_POST["streetname"];
         wp_redirect($url); }
} 
elseif ($result->num_rows == 1) {
   while($row = $result->fetch_assoc()) {
             $url = $row["URL"];
         wp_redirect($url);}
}
else {
   echo '<strong>We do not provide service to this area.</strong>';
   $conn->close();
}
}
}
?>

Upvotes: 0

Views: 293

Answers (1)

J Hock
J Hock

Reputation: 129

The second form is posting back to this page and it doesn't appear the zip code is being passed with the second form

Upvotes: 1

Related Questions