php - 如何使用 PHP 从下拉菜单中动态创建的表单中获取值?

标签 php html mysql

我正在尝试构建一个应用程序,该应用程序将根据用户输入的邮政编码将用户引导至不同的网站。为了缩小范围,在某些情况下,用户可能需要从动态创建的街道名称下拉列表中进行选择。该应用程序使用 PHP 和 mySQL 数据库。我遇到的问题在 PHP 部分下的代码注释中有详细说明。如果可能,请提供PHP驱动的解决方案。如果 jQuery、Javascript、AJAX 等是唯一的选择,请给我一些例子,说明我将如何在这个例子中实现它。谢谢!

这是 HTML 片段:

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

这是通过单击“提交”按钮调用的 PHP:

<?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();
}
}
}
?>

最佳答案

第二个表单正在发回此页面,但似乎没有通过第二个表单传递邮政编码

关于php - 如何使用 PHP 从下拉菜单中动态创建的表单中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29266234/

相关文章:

php - 将utf-8字符串插入数据库然后输出到网页的问题

php - 如何让 .ics 适用于 Outlook(Laravel 邮件程序)?

php - Zend_Session/Zend_Auth 随机抛出错误消息 ps_files_cleanup_dir : opendir(/var/lib/php5) failed: Permission denied (13)

php - 自动缩小和缓存CSS

php - 从 Mysql 检索日期并将其溢出到特定列表

android - 用于网页的 CardView

jQuery 下拉问题

mysql - 如何仅执行 sql 脚本才能获得 Flyway Java 迁移?

php - 使用在 PHP 中连接的生物识别技术创建 Android 出勤监控应用程序

mysql - 在 CakePHP 1.2 中显示 Oracle 分页查询