![](/img/trans.png)
[英]Jquery autocomplete and PHP: populating input field with data from mySQL database based on selected option in autocomplete field
[英]Get variable from database table column into input field based selected option from option field
我已經成功地從我的表中檢索了兩列,並在我的表單中將結果顯示為選擇標簽中的選項。
問題是我無法根據所選選項將第三列中的數據顯示到輸入字段中,該字段也在表單中。
數據庫連接或檢索 select 標記中選項的數據沒有問題。
任何幫助,將不勝感激。 相關代碼如下。
<div class="col-md-4 col-12 bottommargin-sm">
<label for="">Choose currency</label>
<select class="form-control" id="exampleFormControlSelect1">
<option value="">Choose currency...</option>
<?php
// Including DB connection file
include_once "config/config.php";
// Retrieving all columns from currency table
$result = mysqli_query($con, "SELECT * FROM currency_test");
// Loop printing options with country and currrency for all rows in currency table
while($row = mysqli_fetch_array($result)) {
print "<option>";
echo $row['country'] . " - " . $row['currency'];
print "</option>";
}
// Closing DB connection
mysqli_close($con);
?>
</select>
</div>
<div class="col-md-2 col-12 bottommargin-sm">
<label for="">Currency rate</label>
<input type="text" class="form-control" value="<?php echo $row['buy_rate'] ?>" readonly>
</div>
附加編輯
我現在正在使用以下代碼,但仍然沒有任何運氣:
<div class="col-md-4 col-12 bottommargin-sm">
<label for="">Choose currency/label>
<select class="form-control" id="exampleFormControlSelect1">
<option value="default">Choose currency...</option>
<?php
// Including DB connection file
include_once "config/config.php";
// Retrieving all columns from currency table
$result = mysqli_query($con, "SELECT * FROM currency_test");
// Loop printing country, currrency, buy_rate and sell_rate for all rows in currency table
while($row = mysqli_fetch_array($result)) {
echo "<option value=".$row['currency']."> ".$row['country']. " - " .$row['currency']." </option>";
}
?>
</select>
</div>
<div class="col-md-2 col-12 bottommargin-sm">
<label for="">Currency rate</label>
<input type="text" class="form-control" value="<?php echo $row['buy_rate'] ?>" readonly>
</div>
<?php
// Closing DB connection
mysqli_close($con);
?>
如前所述,您在上面的 while 循環中有一個結果 SET,但您希望輸入字段只包含一個值:所選貨幣的購買率。 如果我猜對了,這就是你想要的,這不會像這樣工作。
如果您想測試它並且只在您的 while 循環中檢索單個值,那么您的輸入字段也會填充正確的購買率。
您可以使用或不使用 JavaScript 來實現,但是您需要第二個語句來檢索您想要的購買率。
進一步的安全建議:您不應該使用沒有 __ DIR __ 的包含指令。 你也不應該使用“SELECT * ...”。 最好是命名要檢索的所有字段。
您必須有該選擇的聲明。 (提示:同樣在標簽中,您必須設置一個 value 屬性)如果您使用提交按鈕,您的選擇也需要一個名稱。
現在,當您提交表單時,您可以查詢數據庫並顯示正確的記錄。
如果您不想使用提交按鈕並通過選擇更改文本字段中的值,您將需要 javascript。
所以我看到的是:
1) 選擇標簽中沒有名稱
<select class="form-control" id="exampleFormControlSelect1">
沒有名稱屬性。 所以在發布表單后,服務器不知道變量的名稱。
2) 沒有價值
print "<option>";
您不提供值。 因此,您的服務器在發布表單后不知道該值(用戶選擇的)。
這是選擇標簽的正確方法: https : //www.w3schools.com/tags/tag_select.asp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.