使用从 table 的查询中获得的数据动态更改 html select 表单元素中的选项

Dynamically change the options in an html select forms element with data obtained from a query on a table

我正在尝试制作一个表单,用户可以在其中填写客户的姓氏,然后程序需要使用输入的姓名在数据库中搜索任何具有相同姓氏的客户。然后 select 表单元素需要填充查询结果,允许用户 select 正确的客户信息。 selected 正确的客户后,需要执行另一个查询来搜索单独的 table,以获取与 selected 客户的客户 ID 关联的所有地址。

流量 *用户输入客户姓氏 *查询以获取所有具有相同姓氏的客户 **select 框中填充了客户数据 *用户 selects 正确的客户 *查询查找具有相同客户 ID 的所有地址 **单独的 select 框填充了第二个查询结果

我想用 ajax

完成这个

PRG 模式

引起我注意的第一件事与您的实际问题无关,但确实在调试中发挥了作用。引起我注意的是

if (isset($_POST['search_button'])){

after HTML 输出已经开始。根据经验,POST 变量应该在顶部使用,并且总是重定向(ajax 除外)。查看 Post-Redirect-Get 模式。

但是,在这种情况下,您应该使用 GET,因为您没有更改数据,只是读取特定数据。

这让我进入了调试步骤

分离逻辑和表示

首先执行所有逻辑,然后当所有这些都完成后,关闭 php 并编写您的 html(演示文稿),使用 php 仅用于模板(循环,填写变量,次要陈述条件)

这在调试时非常有用,因为您不必挖掘无关的 html 代码。

因此您的代码可以重新排序为:

<?php

if (isset($_GET['search_button'])){
    require_once "/home/users/web/b1240/dom.heather93124/public_html/resources/config.php";
    
    $fName = $_GET['fName'];
    $lName = $_GET['lName'];
    
// more code here
}
// any other code here
?>
<html>
    <!— and so forth —>

准备好的语句

学习更好的安全性的时间是现在。此查询对 sql 注入是完全开放的。永远,永远,永远不要将原始变量放入查询中。您应该使用准备好的语句,其中用户数据与查询分开处理。此示例假设您有一个 PDO 连接 $pdo.

$stmt = $pdo->prepare("SELECT * FROM Customers Where FirstName LIKE ? AND  LastName LIKE ?");
$stmt->execute(
    [
        $_GET['fName'],
        $_GET['lName']
    ]
);

// iterate through results with $stmt->fetch()

合并此更改将修复代码中的错误。 ($search->fetch... 是一个错误)

总结

<?php

if (isset($_GET['search_button'])) {
    require_once "/home/users/web/b1240/dom.heather93124/public_html/resources/config.php";

    $stmt = $pdo->prepare("SELECT * FROM Customers WHERE FirstName = ? AND  LastName = ?");
    $stmt->execute(
        [
            $_GET['fName'],
            $_GET['lName']
        ]
    );
}
?>
<HTML>
... snip ...

     <div class="form-popup" id="newApp">
        <form  method="get" class="form-container">
            <h1>New Appointment</h1>
            <label for="emp_select"><b>Select Employee</b></label>
                <select id = "emp_select" name="emp_select0">
                    <?php
                        include "/home/users/web/b1240/dom.heather93124/public_html/resources/employee.php";
    
                    ?>
    
                </select><br>
            <input type="text" name="fName" id="fName" placeholder="First name">
            <input type="text" name="lName" id="lName" placeholder="Last name"><br>
            <input type="button" class = "btn" value="Search" name="search_button"></button><br>  
            <select id = "custSelect" name="custSelect0">
            <?php while($row = $stmt->fetchObject()): ?>
                <option value="<?= $row->CustId ?>"><?= $row->fName ?> <?= $row->lName ?></option>
            <?php endwhile; ?>

... snip ...

请注意,这尚未经过测试,您可能需要根据自己的喜好调整 pdo 选项。

我想通了。在这里。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="form-popup" id="newApp">
    <form  method="post" class="form-container" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        <h1>New Appointment</h1>
        <label for="emp_select"><b>Select Employee</b></label>
            <select id = "emp_select" name="emp_select0">
                <?php
                    include "/home/users/web/b1240/dom.heather93124/public_html/resources/employee.php";

                ?>
            </select><br>

        <input type="text" name="lName" id="lName" placeholder="Last name" onkeyup="showCustomer(this.value)"><br>

        <select id = "custSelect" name="custSelect" onchange="adrSelect(this)">
            <option value="">-- Select Customer--</option>

        </select><br>
        <input type="text" id="cust_id" name="cust_id" placeholder="Customer ID" readonly>
        <input type="text" id="custName" name="custName" placeholder="Customer Name" readonly><br>

        <input stlye="backroundColor:#00000020" placeholder="000-000-00000" type="tel" id="newPhone" name="newPhone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
        <input stlye="backroundColor:#00000020" placeholder="000-000-00000" type="tel" id="newAltPhone" name="newPhone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"><br>

        <select id="addrSelect" name="addrSelect" onchange="addrPicker(this)">
          <option value="">-- Select Customer address--</option>
        </select><br>

        <input type="text" placeholder="#### Street Name" name="newStreet" id="newStreet"  size="40"><br>
        <input type="text" PlaceHolder="City" name="newCity" id="newCity" size="10">
        <input type="text" placeholder="State" name="newState" id="newState" size="5">
        <input type="text" placeholder="Zip" name="newZip" id="newZip" size="5"><br>

        <label for="startDate"><b>Start Date</b></label>
        <input type="date"  name="startDate" id="newStartDate" required><br>

        <label for="startTime"><b>Time</b></label>
        <input type="time"  name="startTime" id="newStartTime" required><br>

        <label for="endDate"><b>End Date</b></label>
        <input type="date"  name="endDate" id="newEndDate"><br>

        <label for="endTime"><b>Time</b></label>
        <input type="time"  name="endTime" id="newEndTime" ><br>

        <label for="status_select"><b>Appointment Status</b></label>
            <select id = "status_select0"name="status_select0">
                <?php
                    include "/home/users/web/b1240/dom.heather93124/public_html/resources/aptStatusSel.php";

                ?>
            </select><br>

        <label for="newReason"><b>Description</b></label><br>
        <input type="text" name="newReason" id="newReason" size="55"><br>

        <button type="submit" class="btn" name="newAppSubmit">Submit</button>
        <input type="reset" class="btn cancel">
        <button type="submit" class="btn cancel" onclick="closeFormNewApp()">Cancel</button>
      </form>
    </div>


    <script>
    function showCustomer(str) {
          //alert("click");
          var LastName = str;
          //var ele = document.getElementById('custSelect');
       //alert (LastName);
       $.ajax({
            url:"getcustomer.php",
            type:"POST",
            data:{customer:LastName},
            dataType: "json",

            success:function(data){
                //alert("Data: " + data + "\nStatus: " + status);

                        $('#custSelect').empty();
                        $('#custSelect').append($('<option>').text("---Select Customer---"));
                        $.each(data, function(key, entry){
                          //alert (key + ":" + entry)
                           $('#custSelect').append($('<option></option>').attr('value', entry.custId).text(entry.fname + " " + entry.lname + " -- " + entry.phone));
                          });
                        }
                      });
                    }


        function adrSelect(ele) {
          // GET THE SELECTED VALUE FROM <select> ELEMENT AND populate form with values related to customer.

          let custID = ele.value;
          //alert(custID);
          $.ajax({
            url: "getPhone.php",
            type: "POST",
            data:{custID:custID},
            dataType: "json",

            success:function(data){
                  //alert("Data: " + data + "\nStatus: " + status);
                  $.each(data,function(key, entry){
                    $('#cust_id').val(entry.custId);
                    $('#custName').val(entry.fname + " " + entry.lname);
                    $('#newPhone').val(entry.phone);
                    $('#newAltPhone').val(entry.altPhone);
                    var custID = $('#cust_id').val();
                    //alert (custID);
                    $.ajax({
                         url:"custAddr.php",
                         type:"POST",
                         data:{custID:custID},
                         dataType: "json",

                         success:function(info){


                                     $('#addrSelect').empty();
                                     $('#addrSelect').append($('<option>').text("---Select Customer Address---"));
                                     $.each(info, function(key, entry){
                                       //alert (key + ":" + entry)
                                        $('#addrSelect').append($('<option></option>').attr('value', entry.propID).text(entry.street + ", " + entry.city + ", " + entry.state + " " + entry.zip));
                                       });
                                     }
                                   });
                                 });
                               }
                             });
                           }

        function addrPicker(ele){
          let propID = ele.value;
          //alert (propID);
          $.ajax({
            url: "addrPicker.php",
            type: "POST",
            data:{propID:propID},
            dataType: "json",

            success:function(data){
              //alert("Data: " + data + "\nStatus: " + status);
              $.each(data, function(key, entry){
                $('#newStreet').val(entry.street);
                $('#newCity').val(entry.city);
                $('#newState').val(entry.state);
                $('#newZip').val(entry.zip);
              });
            }
          });
        }


    </script>

然后调用的脚本都与下面非常相似,只是适应了调用它的那部分代码。这个是addrPicker.php

<?php
  //login to database
  require_once "/home/users/web/b1240/dom.heather93124/public_html/resources/configPDO.php";

  if (isset($_POST['propID'])){
    //Get value of custID variable
    $propID = $_POST['propID'];

    //Declare data variable as array
    $data = array();

    try{
      //SQL query PDO
      $sql = "SELECT * FROM `custAdr` WHERE `propID` = :propID";
      //Set cust ID variable as wildcard
      //$custID = "%$custID%";
      $stmt = $connect->prepare($sql);
      //bind wildcard to sql statements
      $stmt->bindValue(':propID', $propID);
      //Execute sql statements
      $stmt->execute();

      //create associative array with results from query
      while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        $data[] = array(
          'propID' => $row["propID"],
          'street' => $row["streetAdr"],
          'city' => $row["city"],
          'state' => $row["state"],
          'zip' => $row["zip"],

        );
        }

    //echo results back to ajax success function
    echo json_encode($data);
    //catch errors from try statement
    }catch(Exception $e){
      echo $e-getMessage();
    }
}

?>