【问题标题】:php mysqli form - fill inputs from select drop-down updatephp mysqli 表单 - 从选择下拉更新中填写输入
【发布时间】:2020-02-15 18:13:31
【问题描述】:

我有一个 php 网页,我可以从下拉选择字段中进行选择,它会按应有的方式填写该字段,但我在填写一些输入字段时遇到了问题。我花了几天时间尝试在 google 上和其他地方找到的各种不同的解决方案,但很少使用 mysqli 填充的下拉选择字段来填充其他输入字段。我可以让它在填充表格的地方工作,但我需要允许用户修改填充的数据,所以我使用了一个输入字段。

CDC3.php 文件:

   <?php
   include_once 'includes/db_connect.php';
   ?>

   <?php
    $b = intval($_GET['b']);

    $sql="SELECT * FROM Batches WHERE BatchNum = '".$b."'";
    $result = $mysqli->query($sql);
    while ($row = mysqli_fetch_array($result)) {
    }
    ?>

主php文件:

<?php include_once 'includes/db_connect.php'; ?>
<!DOCTYPE HTML>
<html>
<head>
<title>CDC Wash Run Entry</title>
  <script>
  function showBatch(str) {
    if (str == "") {
        document.getElementById("txtMessage").innerHTML = "";
        return;
    } 
    else { 
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtMessage").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","CDC3.php?b="+str,true);
        xmlhttp.send();
    }
}
  </script>
</head>
<body>
<form id="WashForm" name="washform" method="POST">
<h1>CDC Wash Run Entry</h2>
<label for="DateTimeCode">DateTimeCode</label>
 <input name="DateTimeCode" value="<?php echo date('Y-m-d H:i:s'); ?>" required><br>
<label for="BatchNum">BatchNum</label>

    <?php
    $sql = "SELECT BatchNum, BatchName, SourceProduct, SourceIngredient FROM Batches ORDER by BatchNum DESC";
    $result = $mysqli->query($sql);
    echo "<select name='BatchNum' id='BatchNum' onchange='showBatch(this.value)'>";
    echo "<option value=''> Select BatchNum        </option>";
    while ($row = $result->fetch_assoc()) {
        echo "<option value='" . $row['BatchNum'] . "'>" . $row['BatchNum'] .' - '. $row['BatchName'] . "</option>";
    }
    echo "</select><br><br>";
    echo "<label for='BatchName'>Batch Name</label>";
    echo " <input name='BatchName' value='".$row['BatchName']."'><br>";
    echo "<label for='SourceProduct'>Source Product</label>";
    echo " <input name='SourceProduct' value='".$row['SourceProduct']."'><br>";
    echo "<label for='SourceIngredient'>Source Ingredient</label>";
    echo "<input name='SourceIngredient' value='".$row['SourceIngredient']."'><br>";
    ?>


</form>        
</body>
</html>

工作的、修改过的代码,对不起代码墙,但它可以工作


数据库/includes/psl-configPDO.php 文件

<?php
$servername = "localhost";
$username = "DBadmin";
$password = "xxxxxxxx"; 
$dbname = "CDCtest";
?>

database/includes/db_connect_PDO.php 文件(从命令行工作)

<?php
require_once('psl-configPDO.php');
try{
    $dbh = new PDO('mysql:host='.$servername.';dbname='.$dbname,$username,$password);
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
    die(json_encode(array('outcome' => false, 
                          'message' => 'Unable to connect to '.$servername.':'.$dbname.' with '.$username)));
}
$dbh = null;
?>

database/includes/jquery.min.js 是https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js的wget


数据库/CDC_Ajax_PDO.php 文件

?>
<?php
require_once('includes/psl-configPDO.php');
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname,$username,$password);
$sth = $db->prepare('SELECT BatchName, SourceProduct, SourceIngredient FROM Batches WHERE BatchNum =:BatchNum');
$sth->bindParam(':BatchNum', $_POST['BatchNum'], PDO::PARAM_INT);
$sth->execute();
$data = new stdClass;
$status = 'failed';
if ($row = $sth->fetchObject() ) {
    $data = $row;
    $status = 'success';
    }
header('Content-Type: application/json');
echo json_encode([
    'status' => $status,
    'data' => $data
    ]);
?>

数据库/CDC_WashFormPDO.php 文件

<?php
require_once('includes/psl-configPDO.php');
$pdo = new PDO('mysql:host='.$servername.';dbname='.$dbname,$username,$password);
$db = $pdo->prepare("SELECT BatchNum, BatchName FROM Batches ORDER by BatchNum DESC");
$db->execute();
?>

<!DOCTYPE HTML>
<html class="supernova"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta property="og:title" content="CDC Wash Run Entry" >
<meta property="og:description" content="Please click submit to complete this form.">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta name="HandheldFriendly" content="true" />
<link type="text/css" rel="stylesheet" href="styles/main.css" />
<head>
 <title>CDC Wash Run Entry</title>
 <script src = includes/jquery.min.js></script>
</head>
<body>
<form class="jotform-form" accept-charset="utf-8" id="WashForm" name="washform" method="POST">
<div class="form-all">
  <ul class="form-section page-section">
    <li id="cid_1" class="form-input-wide" data-type="control_head">
      <div class="form-header-group ">
        <div class="header-text httal htvam">
          <h1>CDC Wash Run Entry</h2>
          <label class="form-label form-label-top form-label-auto">Logged in as: <?php echo htmlentities($_SESSION['username']); ?> </label>
        </div>
      </div>
    </li>
    <li class="form-line" data-type="control_textbox">
        <label class="form-label form-label-top form-label-auto" for="DateTimeCode">DateTimeCode</label>
        <div class="form-input-wide">
          <input type="text" class="form-control" size="20" name="DateTimeCode" value="<?php echo date('Y-m-d H:i:s'); ?>" required>
        </div>
    </li>
    <li class="form-line" data-type="control_dropdown">
        <label class="form-label form-label-top form-label-auto" for="choose-batch">Choose a Batch</label>
        <div class="form-input-wide">



        <select class='form-dropdown' id='choose-batch'>
          <?php while($row = $db->fetchObject()): ?>
// show both name and number in drop-down
        <option value="<?= $row->BatchNum ?>" ><?= $row->BatchNum." - ".$row->BatchName ?></option>
          <?php endwhile; ?>
          </select>



       </div>
    </li>
    <li class="form-line" data-type="control_textbox">
        <label class="form-label form-label-top form-label-auto" for="BatchName">Batch Name</label>
        <div class="form-input-wide">

          <input type='text' class='form-control' size='20' id="BatchName" name="BatchName" value="<?php echo $row['BatchName'];?>" />

      </div>
    </li>
    <li class="form-line" data-type="control_textbox">
        <label class="form-label form-label-top form-label-auto" for="SourceProduct">Source Product</label>
        <div class="form-input-wide">
          <input type="text" class="form-control" size="20" id="SourceProduct" name="SourceProduct" value="" required>
        </div>
    </li>
    <li class="form-line" data-type="control_textbox">
        <label class="form-label form-label-top form-label-auto" for="SourceIngredient">Source Ingredient</label>
        <div class="form-input-wide">
          <input type="text" class="form-control" size="20" id="SourceIngredient" name="SourceIngredient" value="" required>
        </div>
    </li>
  </ul>
    <ul class="form-section page-section" >
    <li class="form-line" data-type="control_text" >
      <div class="buttonrow">
        <div class="col-1 form-buttons-wrapper">
            <button type="submit" class="form-submit-button" id="submit_form" name="submit" value="Submit">Submit</button>
        </div>
      <div class="col-1 form-buttons-wrapper">
         <a href="CDChome.php" >
           <button type="button" class="form-submit-button" >
             Home
           </button>
         </a>
       </div>
       <div class="col-1 form-buttons-wrapper">
          <a href="includes/logout.php">
            <button type="button" class="form-submit-button" >
              Logout
            </button>
          </a>
        </div>
      </div>
    </li>
  </ul>
</div>
</form>        

  <script>
    // monitor for changes in drop-down
    $(document).ready(function() {  // technically not necessary if script is at the bottom, but I do it out of habit
      $('#choose-batch').on('change', function() {
        retrieveItem( $(this).val() );
      })
    });
    // send batchNum via ajax
    function retrieveItem(BatchNumber) {
      $.post(
        "CDC_Ajax_PDO.php",               // where to send data
        {BatchNum: BatchNumber},  // parameters to send {varname: value}
        function(result) {        // what to do with results
          if(result.status=='success') {
            populateForm(result.data);
          } else {
            alert ('oops, failed');
          }
        }
      );
    }
    // put results into page
    function populateForm(data) {
      $('#BatchName').val(data.BatchName);
      $('#SourceProduct').val(data.SourceProduct);
      $('#SourceIngredient').val(data.SourceIngredient);
    }
  </script>



</body>
</html>

【问题讨论】:

  • 如果您有后续问题,请将其作为新问题发布,而不是将其编辑到不会被看到的问题中。
  • 我没有后续问题,我正在发布我的解决方案进展状态,我们已经接近。
  • 它现在可以工作了,非常感谢@Tim-Morton
  • 请不要将工作代码添加到问题中。

标签: php forms mysqli onchange


【解决方案1】:

由于您才刚刚开始,这里有一些概念将使您的旅程更加愉快

  • 必须了解如何使用准备好的语句,而不是将变量放入查询中。尽管在这种情况下intval() 应该是安全的,但您只是不想养成以这种方式编写查询的习惯。恕我直言,PDO 比 mysqli 更易于学习和使用。

  • 使用 javascript 库(如 JQuery)将使 ajax 和客户端脚本大大更容易,并且是跨浏览器兼容的。

  • 在执行 ajax 时,请尝试始终将数据作为 json 编码的字符串传递。您的 ajax 回复是数据,而不是演示。

  • 1234563底端。

话虽如此,您的 CDC3.php 脚本看起来像这样(最佳做法是将 DB 连接对象移动到其自己的文件中,这样您就不会重复自己)

<?php

// connection example, see http://https://phpdelusions.net/pdo
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}


$stmt = $pdo->prepare('SELECT BatchNum, BatchName, SourceProduct, SourceIngredient FROM Batches WHERE BatchNum = ?');
$stmt->execute($_POST['batchNum']);

// initialize $data and $status, in case there are no results
$data = array();
$status = 'failed';
if ($row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    $data = $row;
    $status = 'success';
}

header('Content-Type: application/json');
echo json_encode([
    'status' => $status,
    'data' => $data
    ]);

这会返回您的客户端 javascript 可以接收的数据,这些数据可以立即操作或插入到 dom 元素中。

您的视图看起来像这样(我不确定您在示例中做了什么,所以这将选择一个要显示的批次):

<?php

// connection example, see http://https://phpdelusions.net/pdo
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

$stmt = $pdo->prepare("select BatchNum, BatchName from Batches");
$stmt->execute();

// if you were using regular submits back to the same page, you would deal with them here.

?>
<html>
  <head>
    <title>jQuery CDN</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  </head>
  <body>
    <h1>CDC Wash Run Entry</h1>
    <div>Batch will be loaded by ajax and displayed in the form below:</div>
    <label for="choose-batch">Choose a Batch</label>
    <select id='choose-batch'>
    <?php foreach($stmt as $row): ?>
        <option value="<?= $row['BatchNum'] ?>" ><?= $row['BatchName'] ?></option>
    <?php endforeach; ?>

    </select>

    <form id="batch-form">
      <div>
        <label for='batch-name'>Batch Name</label>
        <input id="batch-name" name='BatchName' value="">
      </div>
      <div>
        <label for='SourceProduct'>Source Product</label>
        <input id="source-product" name='SourceProduct' value="">
      </div>
      <div>
        <label for='SourceIngredient'>Source Ingredient</label>
        <input id="source-ingredient" name='SourceIngredient' value="">
      </div>
    </form>



  <script>

    // monitor for changes in drop-down
    $(document).ready(function() {  // technically not necessary if script is at the bottom, but I do it out of habit

      $('#choose-batch').on('change', function() {
        retrieveIngredient( $(this).val() );
      })
    });

    // send batchNum via ajax
    function retrieveIngredient(batchNumber) {

      $.post(
        "CDC3.php",               // where to send data
        {batchNum: batchNumber},  // parameters to send {varname: value}
        function(result) {        // what to do with results
          if(result.message=='success') {
            populateForm(result.data);
          } else {
            alert ('oops, failed');
          }
        }
      );
    }

    // put results into page
    function populateForm(data) {
      $('#batch-name').val(data.BatchName);
      $('#source-product').val(data.SourceProduct);
      $('#source-ingredient').val(data.SourceIngredient);
    }
  </script>
  </body>
</html>

注意:这是为了展示概念,而不是剪切和粘贴示例。它不在我的脑海中,可能有明显的错误......

【讨论】:

  • 这将用于无法访问互联网的地方,因此无法链接到 googleapis.com...我真的不想将我所有的编程都更改为 PDO...不过谢谢!
  • 我正在尝试从您的代码示例中收集一些有用的提示,但是您更改了这么多,我无法理解您在做什么,我会尝试更深入地研究您所做的事情,再次,我感谢您的努力。
  • 你可以下载jquery,为了简单,我只是使用了cdn。数据库代码是展示prepared statements的示例; mysqli 支持准备好的语句(因此得到了改进),但 pdo 将它放入一个更有用的接口中。就个人而言,我必须在工作中支持几种不同的连接类型,所以我做的第一件事就是为每种类型编写一个对象,这样我的脚本就不必与所有的特质混为一谈……
  • 我认为代码中有太多变化,而且有些地方不熟悉 PDO 会掉进坑里……我花了 12 个小时试图将它集成到我的页面中,其中一半那是在学习初学者 PDO 代码示例,我什至无法加载页面...感谢您的帮助,但这很令人沮丧...
  • 我可能一次介绍的东西太多了。你可能已经错过了这个例子是 *like PDO,但它不是,它只是伪代码(Database 是一个自定义对象,它为我简化了数据库访问)我将编辑我的回答以尝试使其更接近您的习惯。
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
相关资源
最近更新 更多