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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,