提问人:Like 提问时间:6/13/2023 最后编辑:Like 更新时间:6/13/2023 访问量:56
自动从MySQL数据库中获取产品价格
Fetch Product Price From MySQL Database Automatically
问:
我正在用PHP和MySQL创建一个发票系统。我想要的是让用户能够在下拉字段中选择产品,并且该产品的价格应该从数据库中获取并使用 javascript 自动显示在价格输入字段中。到目前为止,我能够获取产品并将它们显示在下拉字段中。请注意,产品名称和价格都存储在同一个表中。
<div class="col-md-4 mb-3">
<select name="product_name[]" id="live_search" class="form-control" placeholder="product name" required autocomplete="off">
<option value="" selected="selected"></option>
<?php
// fetch products
$sqlCAT="SELECT * FROM products";
$queryCAT=mysqli_query($dbCon, $sqlCAT);
while($result = mysqli_fetch_assoc($queryCAT))
{
$product = $result['product_name'];
$id = $result['product_id'];
?>
<option value="<?php echo $product ?>"><?php echo $product ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-2 mb-3">
<input type="number" name="product_price[]" id="search_result" class="form-control" placeholder="item price" required autocomplete="off">
</div>
答:
0赞
Professor Abronsius
6/13/2023
#1
由于您提供的代码很少,而且几乎没有数据库表详细信息,因此您需要研究和修改以下内容,而不是将其作为工作示例。
以下的本质是:
- 将事件侦听器绑定到将处理事件的元素的合适父元素。在使用 AJAX 向后端 PHP 服务器发送 GET 请求之前,此处的事件侦听器会测试菜单的名称是否正确。
SELECT
change
select
- PHP 脚本拦截查询字符串中包含 an 和 an 的 GET 请求。通过使用该参数,您可以向同一后端脚本触发多个 AJAX 请求,但如果需要,可以使用不同的值。
ID
action
action
action
- 创建预准备语句以缓解使用产品 ID 查询数据库的 SQL 注入攻击,以便您可以找到价格。(您可能有几个项目名称相同,但 ID 会不同,因此使用 ID!
- 使用 将价格发送回 AJAX 回调
exit($price)
- 然后,AJAX 回调更新 HTML 输入元素以显示价格。
<?php
require 'dbcon.php';
if( isset(
$_GET['action'],
$_GET['id']
)){
ob_clean();
switch( $_GET['action'] ){
case 'get-price':
# create the sql that will select the price ( Assumed column is called "price" )
$sql='select `price` from `products` where `product_id`=?';
$stmt=$dbCon->prepare( $sql );
$stmt->bind_param('s',$_GET['id']);
$stmt->execute();
$stmt->bind_result( $price );
$stmt->fetch();
exit( $price );
break;
case 'banana':
$sql='select * from x';
/* etc */
break;
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<div class="col-md-4 mb-3">
<select name="product_name[]" id="live_search" class="form-control" placeholder="product name" required autocomplete="off">
<option selected hidden disabled>Select Product
<?php
$sql="SELECT * FROM products";
$res=mysqli_query( $dbCon, $sql );
while( $result = mysqli_fetch_assoc( $res ) ){
$product = $result['product_name'];
$id = $result['product_id'];
printf('<option value="%s">%s',$id,$product);
}
?>
</select>
</div>
<div class="col-md-2 mb-3">
<input type="number" name="product_price[]" id="search_result" class="form-control" placeholder="item price" required autocomplete="off" />
</div>
<script>
const callback=(r)=>document.getElementById('search_result').value=r
// delegated event listener bound to the document as the full HTML structure is unknown
document.addEventListener('change',e=>{
// if the event was triggered by a SELECT element being changed - proceed
if( e.target instanceof HTMLSelectElement ){
// if the element was the Product select
if( e.target.name=='product_name[]' ){
// send GET request using ID of product and update price displayed in "search_result"
fetch( '?action=get-price&id=' + e.target.value )
.then( r=>r.text() )
.then( callback )
.catch( alert )
}
}
})
</script>
</body>
</html>
这只是一种可能的方法......这可以很容易地修改以处理所有选择元素和其他元素,这将使它更加有用
0赞
Lvn W
6/13/2023
#2
你在问两件事。
- 如何从下拉列表中获取价格值
1.1 为选项添加价格,因为它在同一个表格中,你可以很容易地做到这一点(我猜你的列是如何命名的,所以用正确的值替换$productPrice和$productName)
<option value="<?php echo $productPrice ?>"><?php echo $productName ?></option>
1.2 通过 Js 获取所选选项,并在浏览器控制台中显示以进行演示
<script>
const selector = document.getElementById("live_search");
function onChange() {
const value = selector.value;
const text = selector.options[selector.selectedIndex].text;
console.log(value, text);
}
selector.onchange = onChange;
onChange();
</script>
更新上面的代码片段,通过 JS 通过 value 属性将价格显示到价格输入框中
const selector = document.getElementById("live_search"); const priceField = document.getElementById("search_result"); function onChange() { const value = selector.value; const text = selector.options[selector.selectedIndex].text; priceField.value = value; } selector.onchange = onChange; onChange();
0赞
Like
6/13/2023
#3
我能够用以下代码解决问题。我在产品下拉框中添加了一个事件侦听器函数,并使用 ajax 获取价格并将其附加到价格输入字段。
// get product names and assign the ID in the drop down box
<select name="product_name[]" id="product" class="form-control" placeholder="product name" required autocomplete="off">
<option value="" selected="selected">Select Product</option>
<?php
// fetch product categories
$sqlCAT="SELECT * FROM products";
$queryCAT=mysqli_query($dbCon, $sqlCAT);
while($result = mysqli_fetch_assoc($queryCAT))
{
$product = $result['product_name'];
$id = $result['product_id'];
?>
<option value="<?php echo $id ?>"><?php echo $product ?></option>
<?php } ?>
</select>
其次,我创建了一个文件来获取价格
// get_price.php
if (isset($_GET['id'])) {
$productId = $_GET['id'];
$result = mysqli_query($dbCon, "SELECT product_price FROM products WHERE product_id = $productId");
$row = mysqli_fetch_assoc($result);
// Return the price as JSON
echo json_encode(array('price' => $row['product_price']));
}
最后,我添加了一些javascript
// live search
$("#product").change(function() {
// Retrieve the selected product ID
var productId = $(this).val();
// Send an AJAX request to fetch the product price
$.ajax({
type: "GET",
url: "get_price.php",
data: { id: productId },
dataType: "json",
success: function(response) {
// Update the price input field with the fetched price
$("#price").val(response.price);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
问题解决了
评论