duanru6816 2019-02-21 16:11
浏览 57
已采纳

将HTML PHP PDO绑在一起

I am very new to this and this is my first post to stackoverflow. I am simply trying to: Create a dropdown list that 1) Triggers a query (Gettech.php) everytime it changes 2) Updates another field with the results of the query

In this case they select a "tech name" and it should update another field with the associated "tech number" (result of the PDO query) everytime "tech name" changes. This is what I have:

<!DOCTYPE HTML>  
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form action="Gettech.php" method="get">
<div class="row">
     <div class="col-sm-6 form-group">
       <label for="name"> Name:</label>
       <select class= "form-control" id="techname" name=techname><option value="">Select...</option>
       <option value="First Name">First Name</option>
       <option value="Second Name">Second Name</option>                       .
        .
        .
       </select>
</div>
</form>
</body>
</html>

and the Gettech.php part

<?php
$servername = "localhost";
$username = "####";
$password = "####";
$name = "Joey";
try {
     $db = new PDO('mysql:host=localhost;dbname=staff', $username, $password);
    } catch (PDOException $e) {
    echo $e->getMessage()."<br>";
    die();
    }
$sql = "SELECT name, techid from techs where name= '$name'";
foreach( $db->query($sql) as $row ) {
echo $row['name']."<br>".$row['techid']."<br>";
                                    }
$db = null;
?>

Individually they work but don't know how to tie them together into a working solution. Hints are welcome!

</div>
  • 写回答

1条回答 默认 最新

  • douqiandai4327 2019-02-21 18:35
    关注

    Based on your description of what you are trying to do, you really need to do this with Javascript/JQuery. I have not tested this code but just hoping to get you on the right path. Please visit https://learn.jquery.com/ajax/jquery-ajax-methods to learn about AJAX.

    HTML

    <!DOCTYPE HTML>  
    <html>
        <head>
              <meta charset="utf-8">
              <meta name="viewport" content="width=device-width, initial-scale=1">
              <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
              <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
              <script src="js/ajax.js"></script>
        </head>
        <body>
            <form>
                <div class="row">
                    <div class="col-sm-6 form-group">
                       <label for="name"> Name:</label>
                       <select class="form-control" id="techname" name=techname>
                       <option value="">Select...</option>
                       <option value="First Name">First Name</option>
                       <option value="Second Name">Second Name</option>
                        .
                        .
                       </select>
                    </div>
                </div>
            </form>
            <div id="content"> <!-- AJAX DATA --> </div>
        </body>
    </html>
    

    PHP

    <?php
    $servername = "localhost";
    $username = "####";
    $password = "####";
    $name = "Joey";
    try {
            $db = new PDO('mysql:host=localhost;dbname=staff', $username, $password);
    } catch (PDOException $e) {
        $error = [
            'status' => "error",
            'error'  => $e->getMessage()
        ];
    
        return json_encode($error);
    }
    
    // Sanitize and validate this for security & integrity purposes
    if (isset($_GET['name'])) {
        $name = $_GET['name'];
    } else {
        $error = [
            'status' => "error",
            'error'  => "$_GET not received"
        ];
    
        return json_encode($error);
    }
    
    $sql = "SELECT name, techid FROM techs WHERE name = :name";
    // Make sure you are using prepared statements, 
    // it's one of the most powerful security features of PDO
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':name', $name, PDO::PARAM_STR);
    $stmt->execute();
    
    // You need to "fetch" the result before you can use it
    $result = $stmt->fetchAll();
    
    $db = null;
    
    foreach($result as $key => $row) {
        $html .= "<div>{$row['name']}</div>";
        $html .= "<div>{$row['techid']}</div>";
    }
    
    $data = [
                'status' => "success",
                'html'   => $html
            ];
    
    return json_encode($data);
    ?>
    

    ajax.js

    // Wait for DOM to be ready
    $(function() {
        $('#techname').on('change', function(e) {
    
            // Prevents page from reloading
            e.preventDefault();
    
            var value = $("option:selected", this).val();
    
            $.ajax({
                type: "GET",
                // If file is not in docroot, you need to specify the subdirectory
                url: "Gettech.php",
                dataType: "JSON",
                data: value.serialize(),
                beforeSend: function() {
                    // Good idea to put a loader here so the user knows 
                    // something is happening if request takes time
                    $('.loading').fadeIn('fast');
                },
                success: function(result) {
    
                    if (result.status === "error") {
                        var data = result.error;
                    } else if (result.status === "success") {
                        var data = result.html;
                    }
    
                    // Hide the loader once completed
                    $('.loading').fadeOut('fast');
    
                    // Add query data to the DOM
                    $('#content').html(data);
                }
            });
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler