我的代碼有問題。我試圖用數據庫中的數據填充textbox
。它需要在我的dropdownmenu
中顯示所選項目的價格。但它不起作用。我可以填寫我的dropdownmenu
,但是當我選擇一個項目時,我的textbox
保持空白。當選擇下拉菜單填充數據庫中的數據的文本框
我使用下面的表結構:
forms (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sort` int(1) NOT NULL,
`name` varchar(100) NOT NULL,
`price` decimal(7,2) NOT NULL,
`tax` int(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
// index.php文件
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM database";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<!-- Your text input -->
<input id="product_name" type="text">
</html>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.select2 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo json_encode($result['price']);
}
else
{
echo json_encode('no results') ;
}
}
?>
有人可以幫助我解決這一問題?
哪裏'product1'來到$從你似乎在設置'$ productId' – RST
'$ product1'必須是正確的,我在代碼中改變了它。但它仍然不起作用 – John
你拼錯'取'' – RST