php mysqli 表单 - 从 select 下拉更新中填写输入

php mysqli form - fill inputs from select drop-down update

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

TheCDC3.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>

修改后的工作代码,对代码墙感到抱歉,但它确实有效


database/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

database/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
    ]);
?>

database/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>

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

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

  • 使用 javascript 库,例如 JQuery 将使 ajax 和客户端脚本 很多 更简单,并且跨浏览器兼容。

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

  • 对于非 mvc 脚本,尝试将所有 php 放在顶部(初始化、使用用户 input/redirection 和业务逻辑),然后才 html(php 仅用于循环和数据替换)在底部。

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

<?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 可以接收此 returns 数据作为数据,它可以立即处理或插入 dom 元素。

你的视图看起来像这样(我不确定你在你的例子中做了什么,所以这将 select 一批显示):

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

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