У меня есть веб-страница 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>
Рабочий, модифицированный код, извините за стену кода, но он работает
База данных / включает в себя /файл psl-configPDO.php
<?php
$servername = "localhost";
$username = "DBadmin";
$password = "xxxxxxxx";
$dbname = "CDCtest";
?>
База данных / файл / 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;
?>
База данных / включает в себя/jquery.min.js - это wget из https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
файла базы данных / 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>