php - 将 HTML PHP PDO 结合在一起

标签 php html mysql pdo

我对此很陌生,这是我在 stackoverflow 上发表的第一篇文章。 我只是想: 创建一个下拉列表 1)每次更改时触发查询(Gettech.php) 2)用查询结果更新另一个字段

在这种情况下,他们选择一个“技术名称”,并且每次“技术名称”更改时,它都应该使用关联的“技术编号”(PDO 查询的结果)更新另一个字段。这就是我所拥有的:

<!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>

和 Gettech.php 部分

<?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;
?>

他们各自工作,但不知道如何将它们结合在一起形成一个可行的解决方案。欢迎提示!

最佳答案

根据您对尝试执行的操作的描述,您确实需要使用 Javascript/JQuery 来执行此操作。我还没有测试过这段代码,只是希望能让您走上正确的道路。 请访问https://learn.jquery.com/ajax/jquery-ajax-methods了解 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);
            }
        });
    });
});

关于php - 将 HTML PHP PDO 结合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54811506/

相关文章:

php - 如何使用jquery ajax通过单击将复选框值传递给php

javascript - Struts2提交按钮绑定(bind)进入

javascript - 在 HTML5 Canvas 上创建颜色选择器

mysql - 将mysql数据导入到solr

mysql - 选择同时喜欢苹果和香蕉的人

php - Android中的加密相当于php的MCRYPT_RIJNDAEL_256

php - 如何加速数百万个项目的BETWEEN操作?

php - 如何判断脚本是否从 WordPress 中的插件、主题或子主题执行?

html - 图像内联部分的重建。

mysql - 仅在先购买另一种产品后才获取该产品?